Showing posts with label Tip. Show all posts
Showing posts with label Tip. Show all posts

Monday, December 12, 2011

Tip 1 - Exception Logging in Java

TIP #1 - Always Use The toString() Method Of The Exception Class Instead Of getMessage().

One of the common patterns in exception logging that I see a lot (and I've used it myself) is

catch(Exception e)
{
    logger.error ("Exception Message : " + e.getMessage());
}

The problem with e.getMessage() is that for lot of Exceptions (including many thrown by in build java classes) its value is either null or a cryptic string. Without any information on the exception type it makes it very difficult to determine what actually went wrong.

Consider these rather simple example

  • when a null pointer exceptions is thrown

    //Exception Message : null
    System.out.println("Exception Message : " + e.getMessage());
    
    //Exception Message : java.lang.NullPointerException
    System.out.println("Exception Message : " + e.toString());
    

  • when an Number Format Exception is thrown

    //Exception Message : For input string: "x"
    System.out.println("Exception Message : " + e.getMessage());
    
    //Exception Message : java.lang.NumberFormatException: 
    For input string: "x"
    System.out.println("Exception Message : " + e.toString());
    
Which of the two messages would you rather see in your logs?

These example are typical of what e.getMessage() returns and without the Exception type the message-text is just a cryptic text value.