In java coding, we used to have try-catch statement mainly for capturing unforeseen code errors such as SQL query error, parsing a non number to number and as such.
Normally within the catch, we will either throw it back to the method that calls it, or print it out using printStackTrace(). If we were to print it to a string or a log file, we will use toString(). But then, printing to a log file using toString() method might not be sufficient for a developer.
[12:34:56] java.lang.NullPointerException
What does this means? I know the application is hitting some variables which had not been assigned to any value, but where is it? I had a thousand lines of code, which is hitting the error? My current catch is as such:
catch (Exception e) {
log.error(e.toString());
throw e;
}
Well, to get a better description on the log file, I would recommend to use these code instead of just e.toString():
catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.close();
log.error(sw.toString());
throw e;
}
These code will actually write the more descriptive printStackTrace() to a buffer, and we print the buffer out instead of writing it somewhere else. With these code, I am able to get better description, including which line and what class as such:
[12:34:56] java.lang.NullPointerException
at a.class.package.anotherMethod(NewClass2.java:87)
at a.class.package.newMethod(NewClass.java:890)
at a.class.package.main(NewClass.java:60)
Exception in thread "main"
Isn't it better than a single line printout?
2 comments:
ya it definitely is better, sifu
Thanks for the complement sifu.
Post a Comment