Wednesday, September 8, 2010

FindBugs Warning - Exception is caught when exception is not thrown

Performing static analysis of a Java code-base on a regular basis is an extremely useful exercise, and I have found FindBugs to be an extremely useful and worthy tool. One particular warning raised by FindBugs - exception is caught, when exception is not thrown - may appear to be a false positive at first, however, the tool basically recommends catching specific exception types, instead of having a "catch all" exception clause that catches the base Exception class.

The reason for this is pretty simple - catching the base Exception class will also catch the RuntimeException, which is a child class of Exception. This will mask potential programming mistakes. As a result of having a catch clause with the base Exception class, I have seen instances of NullPointerException - a child of RuntimeException - being caught and logged on numerous occasions. This potentially masks problems in the code, when an object instance was null, although it wasn't supposed to be so. If the object is null in only certain circumstances, then there is a distinct possibility that catching the base Exception will cause this problem to slip by in the development environment and fail in a production set-up at a customer site.

Catching specific exceptions and handling them appropriately - and perhaps differently - also makes for a better error-handling approach. Overall, it improves the readability of the code, where others are able to better understand and extend the exception handling mechanism.

Not long ago there was a trend among Java programmers to use the "*" notation while importing packages - e.g. java.util.*, instead of explicitly importing the classes required. This trend seems to have disappeared, and I hope that the trend of catching the base Exception class also cedes to the approach of explicitly catching the specific exceptions.

1 comment:

  1. I agree that is it NOT a good idea to 'handle' an Exception like any other if you are too lazy to spell out the different exceptions that can occur.
    But if you want to catch and log programming mistakes with the purpose of fixing any undetected bug then you WILL need a catch Exception! Or is there a better way?

    ReplyDelete