Throws or try-catch
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.
- 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)
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
usesHibernate
for persisting my entities, so I catch allHibernateExceptions
locally and convert them into my own exception types).