Best Practice for exception handling

  • Catch subclass exception first.
  • Throw an exception early
The exception stack trace helps you pinpoint where an exception occurred by showing us the exact sequence of method calls that lead to the exception. By throwing your exception early, the exception becomes more accurate and more specific. Use if(file==null) throw new IllegalArgumentException instead of new FileInputStream(file)
  • Avoid suppressing or ignoring exceptions.
  • Also avoid using exceptions just to get a flow control.
  • Catch the exception at the appropriate layer
You should not try to catch the exception before your program can handle it in an appropriate manner. The natural tendency when a compiler complains about a checked exception is to catch it so that the compiler stops reporting errors. The best practice is to catch the exception at the appropriate layer (e.g. an exception thrown at an integration layer can be caught at a presentation layer in a catch {} block), where your program can either meaningfully recover from the exception and continue to execute or log the exception only once in detail, so that user can identify the cause of the exception. Note: Due to heavy use of checked exceptions and minimal use of unchecked exceptions, there has been a hot debate in the Java community regarding true value of checked exceptions.
  • Use checked exceptions when the client code can take some useful recovery action
  • Use unchecked exception when client code cannot do anything based on information in exception.
For example, convert your SQLException into another checked exception if the client code can recover from it and convert your SQLException into an unchecked (i.e. RuntimeException) exception, if the client code cannot do anything about it.