Throws or try-catch

JavaExceptionException HandlingTry CatchThrows

Java Problem Overview


What is the general rule of thumb when deciding whether to add a throws clause to a method or using a try-catch?

From what I've read myself, the throws should be used when the caller has broken their end of the contract (passed object) and the try-catch should be used when an exception takes place during an operation that is being carried out inside the method. Is this correct? If so, what should be done on the callers side?

P.S: Searched through Google and SO but would like a clear answer on this one.

Java Solutions


Solution 1 - Java

  • catch an exception only if you can handle it in a meaningful way
  • declare throwing the exception upward if it is to be handled by the consumer of the current method
  • throw exceptions if they are caused by the input parameters (but these are more often unchecked)

Solution 2 - Java

In general, a method should throw an exception to its caller when it can't handle the associated problem locally. E.g. if the method is supposed to read from a file with the given path, IOExceptions can't be handled locally in a sensible way. Same applies for invalid input, adding that my personal choice would be to throw an unchecked exception like IllegalArgumentException in this case.

And it should catch an exception from a called method it if:

  • it is something that can be handled locally (e.g. trying to convert an input string to a number, and if the conversion fails, it is entirely valid to return a default value instead),
  • or it should not be thrown (e.g. if the exception is coming from an implementation-specific lower layer, whose implementation details should not be visible to the caller — for example I don't want to show that my DAO uses Hibernate for persisting my entities, so I catch all HibernateExceptions locally and convert them into my own exception types).

Solution 3 - Java

Here's the way I use it:

Throws:

  • You just want the code to stop when an error occurs.
  • Good with methods that are prone to errors if certain prerequisites are not met.

Try-Catch:

  • When you want to have the program behave differently with different errors.
  • Great if you want to provide meaningful errors to end users.

I know a lot of people who always use Throws because it's cleaner, but there's just not nearly as much control.

Solution 4 - Java

My personnal rule of thumb for that is simple :

  • Can I handle it in a meaningful way (added from comment)? So put code in try/catch. By handle it, I mean be able to inform the user/recover from error or, in a broader sense, be able to understand how this exception affects the execution of my code.
  • Elsewhere, throw it away

Note : this replys is now a community wiki, feel free to add more info in.

Solution 5 - Java

The decision to add a try-catch or a throws clause to your methods depends on "how you want (or have) to handle your exception".

How to handle an exception is a wide and far from trivial question to answer. It involves specially the decision of where to handle the exception and what actions to implement within the catch block. In fact, how to handle an exception should be a global design decision.

So answering your questions, there is no rule of thumb.

You have to decide where you want to handle your exception and that decision is usually very specific to your domain and application requirements.

Solution 6 - Java

If the method where the exception got raised has a sufficent amount of information to deal with it then it should catch, generate useful information about what happened and what data was being processed.

Solution 7 - Java

A method should only throws an exception if it can make reasonable guarantees surrounding the state of the object, any parameters passed to the method, and any other objects the method acts upon. For example, a method which is supposed to retrieve from a collection an item which the caller expects to be contained therein might throws a checked exception if the item which was expected to exist in the collection, doesn't. A caller which catches that exception should expect that the collection does not contain the item in question.

Note that while Java will allow checked exceptions to bubble up through a method which is declared as throwing exceptions of the appropriate types, such usage should generally be considered an anti-pattern. Imagine, for example, that some method LookAtSky() is declared as calling FullMoonException, and is expected to throw it when the Moon is full; imagine further, that LookAtSky() calls ExamineJupiter(), which is also declared as throws FullMoonException. If a FullMoonException were thrown by ExamineJupiter(), and if LookAtSky() didn't catch it and either handle it or wrap it in some other exception type, the code which called LookAtSky would assume the exception was a result of Earth's moon being full; it would have no clue that one of Jupiter's moons might be the culprit.

Exceptions which a caller may expect to handle (including essentially all checked exceptions) should only be allowed to percolate up through a method if the exception will mean the same thing to the method's caller as it meant to the called method. If code calls a method which is declared as throwing some checked exception, but the caller isn't expecting it to ever throw that exception in practice (e.g. because it thinks it pre-validated method arguments), the checked exception should be caught and wrapped in some unchecked exception type. If the caller isn't expecting the exception to be thrown, the caller can't be expecting it to have any particular meaning.

Solution 8 - Java

When to use what. I searched a lot about this. There is no hard and fast rule.

"But As a developer, Checked exceptions must be included in a throws clause of the method. This is necessary for the compiler to know which exceptions to check. By convention, unchecked exceptions should not be included in a throws clause.
Including them is considered to be poor programming practice. The compiler treats them as comments, and does no checking on them."

Source : SCJP 6 book by Kathy Sierra

Solution 9 - Java

I ll make it simple for you. Use throws when you think that the called method is not responsible for the exception (e.g., Invalid parameters from the caller method, item to be searched, fetched not available in the collections or fetch datalist). Use try catch block(handle the exception in the called method) when you think that your functionality in the called method may result in some exception

Solution 10 - Java

If you use a try catch, when the exception occurs, the remaining codes would be still executed.

If you indicate the method to throw the exception, then when the exception occurs, the code would stop being executed right away.

Solution 11 - Java

try-catch pair is used when you want to provide customise behaviour, in case if exception occurs.....in other words...you have a solution of your problem (exception occurrence) as per your programme requirements.....

But throws is used when you don't have any specific solution regarding the exception occurrence case...you just don't want to get abnormal termination of your programme....

Hope it is correct :-)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames P.View Question on Stackoverflow
Solution 1 - JavaBozhoView Answer on Stackoverflow
Solution 2 - JavaPéter TörökView Answer on Stackoverflow
Solution 3 - JavaJustian MeyerView Answer on Stackoverflow
Solution 4 - JavaRiduidelView Answer on Stackoverflow
Solution 5 - JavaEijiAdachiView Answer on Stackoverflow
Solution 6 - JavaAlberto ZaccagniView Answer on Stackoverflow
Solution 7 - JavasupercatView Answer on Stackoverflow
Solution 8 - Javasofs1View Answer on Stackoverflow
Solution 9 - JavaKeshav Deo SharmaView Answer on Stackoverflow
Solution 10 - JavaJarkidView Answer on Stackoverflow
Solution 11 - Javauser8148636View Answer on Stackoverflow