Hi, The Exception class getMessage method return a string which we can store and manipulate but the details are pretty little. With printStackTrace, we see a lot more but I can't seem to find any way to store the information printed. Reason for this is that I would want to pass the stack trace detail to a Logger object for logging, instead of printing 'directly' to a file. Any ideas? Thanks in advance.
Joined: Jan 30, 2000
Well, if you're using Java 1.4, this is easy. Exceptions (all Throwables in fact) now have a getStackTrace() method which makes it easy to access all the info in the stack trace. Moreover if you use the java.util.logging.Logger class, you have can use many methods which accept a Throwable as a parameter, which means the Logger knows how to log the stack trace for you without any extra effort on your part (other than passing the parameter.) If you're not using 1.4, whatever logging mechanism you're using (Log4J maybe?) should have methods for logging exceptions. If you're writing the logger yourself, write methods to handle exception info. The best (only?) way to extract a stack trace prior to 1.4 is by printing the stack trace to something that saves the info. The simplest is to use a StringWriter wrapped in a PrintWriter. The latter is necessary because a there's no printStackTrace(Writer), just printStackTrace(PrintWriter). Here's a method to store a stack trace as a String:
"I'm not back." - Bill Harding, Twister
Joined: Aug 09, 2002
Hi Jim, Thanks for the sample code. I'm using jdk 1.3, so I guess that is the only way !