Throws or try-catch
Asked Answered
B

11

83

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.

Bashemeth answered 8/7, 2010 at 12:1 Comment(2)
I've always been a fan of "If it makes sense to deal with it here...then do it" approach.Thrilling
I like to have all my exceptions handled where they occure so I do not have to deal with the down the road.Wishbone
B
67
  • 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)
Bricker answered 8/7, 2010 at 12:5 Comment(3)
Right, the third rule is very clear. About handling an exception in a meaningful way, is this in the higher layers of a program? Does this mean that APIs tend to generally throw Exceptions? Also, in what cases should a method rethrow exceptions coming from submethods (coming from private utility methods for example)?Bashemeth
well, it vastly depends. APIs throw exceptions, yes. But then comes the choice of checked vs unchecked.Bricker
Why rethrow the exception? Just don't catch it and pass it up the call stack.Finsen
W
15

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).
Wistful answered 8/7, 2010 at 12:5 Comment(2)
Ok. To reformulate, an exception would be thrown when an immediate solution isn't possible and some interaction is needed "above" to decide what to do. Also, an exception wouldn't be rethrown if it is only has a "meaning" between a group of classes and a more generalized exception should be thrown in it's place to inform the caller that it's attention is needed. Does this sound more or less right?Bashemeth
@James, more or less :-) If by "interaction" you mean asking user intervention, it is not always needed. Also, instead of "more generalized" I would prefer "different". A user-defined ConnectionException is no more general than HibernateException.Selfwinding
N
12

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.

Nucleoplasm answered 8/7, 2010 at 12:15 Comment(4)
You should almost NEVER use exception handling for program control. It is a terrible practice.Thrilling
There's also Try-catch-rethrow, or try-catch-wrap-throw--i.e., just because you can handle the exception in a meaningful way doesn't mean you're done. The method should do what its name indicates it will do, or should throw an exception: abstractions-r-us.blogspot.com/2010/06/…. (shameless plug for my blog)Bluma
This is a question that I have been wondering for some time. I think that I try and use try-catch blocks if needed with user defined exceptions. Exception. But I will have to say that a throws in the method stub is a lot cleaner and way less code to have to sort through later on if you have to do any debugging. If you use a throws in the method stub you have to trap the error up the chain of methods, I think, this I am not sure of. With a try-catch you can just have the try-catch catch the error without having to pass it up the chain of methods. I am not completely certain on this but I thinkWishbone
This is how it generally goes, I think. I know that with reading files that if you use a try-catch and then declare an instance of your class in another class you do not have to have the method throw the exception. I am still uncertain on this.Wishbone
T
9

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.

Toluca answered 8/7, 2010 at 12:1 Comment(3)
Can I handle it in a meaningful way.Foliate
What are your criteria for deciding if you can handle an exception locally? Is this on the level where you can actually take care of the exception and display a message for example?Bashemeth
Throwing it away is a bad idea. Better is to pass it up the call stack.Finsen
G
3

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.

Grimbald answered 13/6, 2013 at 13:24 Comment(0)
D
2

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.

Dupuy answered 8/7, 2010 at 12:6 Comment(1)
Do you always write the error exception to a logger file or to the console. I was thinking of this last night because in the actually program you will not be able to see the actual console so shouldn't your errors go to a text file. So how does e.printStackTrace() print. I goes to the console when debugging but were else can it go to?Wishbone
S
1

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.

Sandhi answered 13/6, 2013 at 19:16 Comment(0)
G
1

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

Granulite answered 23/12, 2018 at 11:17 Comment(0)
A
1

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

Await answered 19/1, 2021 at 9:0 Comment(0)
A
0

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.

Autochthonous answered 13/3, 2017 at 7:26 Comment(0)
P
0

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 :-)

Pike answered 21/6, 2018 at 17:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.