If You Catch It You Buy It

I recently worked on a defect on a customer site where all the feedback I got from the server was ‘Set Method failed – null.’ The root cause of the defect had little to do with the code the logged this cryptic ‘debug’ message. The root cause was deeper than this; the root cause lied in the bowels of dynamic events that get fired when the ‘Set Method’ gets called. The root cause lied 10 methods down the stack from the point where it was logged. I had no clue as to what code produced what seems to be a NullPointerException. The problem here was not just bad code but bad logs! Log4J provides programmers with a simple API to write debug message that is a prefer way to what some learn in school, the printf method, but I feel that developers often don’t know what to log and even worse how to handle exceptions!! What follows are real live code example, turn away if you are squeamish!!

catch (Exception e) {}
catch (Exception e) {
    //
    // FIXME: This is not very good exception handling
    //
    e.printStackTrace();
}
catch (Exception ex) {
    logger.warning("Exception occurred::");
}

I have proposed the following motto at work: If you break it you buy it, if you catch it you log it! The point is to log everything you catch but most importantly log the root cause of the exception and not some cryptic ‘exception occurred’ message.