Pages

Thursday, December 29, 2011

Exceptions: Best Practices


Last days I had a discussion with few colleagues about best practices on handling exception in the code (more precisely in the JEE application server). As we exposed each one his point of view, we arrived to point the performance issue that may arrive. At that moment, I remembered an older entry on Xebia French blog that illustrated such performance issue related to exception management.

First off all, the author explains that it was not obvious to find the source of its performance problem. Fortunately, he was using an open source framework and he was able to isolate the code causing the problem. In fact there was a method that threw a NoClassDefFoundError at each call. This method body was looking something like that:
try {
 variable = new SomeClass();
} catch (Throwable t) {
    try {
        variable = new SomeNewClass();
    } catch (Throwable t2) {
        variable = new SomeOtherClass();
    }
}
 
I must confess I spent a whole day to find a bug in one of our projects, caused by a similar code in an external jar file that for some reason threw an exception:
try {
 // doing something
} catch (Throwable t) {
};

Another subject that the author illustrates (and the one of the users argued and proved) is that comparing two method calls, one with nominal execution and the other one throwing an exception, there were significant differences on the execution time between the two cases. This is caused, on the one hand by the object creation and on the other hand by the synchronized fillInStackTrace method in Throwable class.

In conclusion, what we have learn from these examples when using exceptions:
  • exceptions must be used in order to handle errors, an exceptional event that disrupts the normal execution of the program; do not use exceptions in order to transfer values, return parameters from methods etc; 
  • if you catch an exception, log an appropriate message or do something that help the debugging
  • do not catch Throwable, Error or RuntimeException (well there may be some exceptions here  :p)

/* */