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());
These example are typical of what e.getMessage() returns and without the Exception type the message-text is just a cryptic text value.
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@Javin - Nice article & Tips. I'm pretty sure I read that article before :). Thanks for leaving the link in the comment!
ReplyDeleteAs 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.
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@extremejava - Some of those questions are really good!
ReplyDeleteI'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!
@Saifuddin, Indeed SLFJ is best choice but some people use commons-logging also.
ReplyDeleteVery Useful Tips...Thanks Saif
ReplyDeleteGlad you found it useful Ram
ReplyDelete