Wednesday, June 9, 2010

Catching Java Exceptions

While running FindBugs - a static analysis tool - on a Java project, I encountered numerous instances of a warning - "Exception is caught when Exception is not thrown". Digging deeper into the problem made me realize that this warning results from a "catch all" exception block - catch(Exception e) - that is very commonly used by most Java developers to avoid handling checked exceptions explicitly.

The reason that FindBugs complains about this practice is that having a catch all block for some code - using catch(Exception e) - also catches RuntimeException, which is a child class of Exception; however, doing so could potentially mask serious errors in the program logic. As an example, having a catch(Exception e) block catches the NPE (NullPointerException), which is a child class of RuntimeException. The NPE exception indicates potential problem with the code, indicating that a defensive null check is missing before an attempt to dereference an object. This problem may go undetected for a while if a "catch all" block is used to catch all exceptions.

The only solution to this problem is to explicitly catch the "checked" exceptions that can be thrown by the executing code. Even though there is a base class for runtime exceptions, there is no such class for checked exceptions, so the developer needs to explicitly catch the different checked exceptions, which may seem like a pain, but would certainly be beneficial in the long run. An additional motivation - for catching all checked exceptions explicitly - is that the method may need to throw each exception explicitly to clearly indicate the problem to the caller, which facilitates better error handling and reporting.