Throws or try-catch Throws or try-catch java java

Throws or try-catch


  • 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 uses Hibernate for persisting my entities, so I catch all HibernateExceptions locally and convert them into my own exception types).


Here's the way I use it:

Throws:

  • You just want the code to stop whenan error occurs.
  • Good with methods that are prone toerrors if certain prerequisites arenot met.

Try-Catch:

  • When you want to have the programbehave differently with differenterrors.
  • Great if you want to providemeaningful 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.