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.

7 comments:

  1. Cool tip, though quite common not aware of it , Instead I always use printStackTrace(). I have also blogged on logging as 10 Tips on logging in Java , let me know how do you find it.

    ReplyDelete
  2. @Javin - Nice article & Tips. I'm pretty sure I read that article before :). Thanks for leaving the link in the comment!

    As for printStackTrace() - I would not normally use that (just as I would never use SOP).
    Its here just for demo purpose.
    For all application we normally use Log4j (or SLF$J).

    There are few occasions when you don't want the entire stack trace showing up in the log and end up with the exception.getMessage(). For those cases I suggest using the exception.toString() instead.

    ReplyDelete
  3. That is something new and innovative. getMessage usually makes the log files hell. Only first few lines of stack trace are important for fixing an issue.10 Challenging Java Programming Questions

    ReplyDelete
  4. @extremejava - Some of those questions are really good!

    I've been looking for a utility that would do just that - get the most relevant part of an exception discarding the other parts of the stack trace. I haven't come across any generic utility that could do something like that, yet!

    ReplyDelete
  5. @Saifuddin, Indeed SLFJ is best choice but some people use commons-logging also.

    ReplyDelete
  6. Very Useful Tips...Thanks Saif

    ReplyDelete

Leave a thought, always good to hear :)