<< Is Math.sqrt expensive? | Home | I just don't get packages and the classpath! >>

Printing a stack trace to a String?

A user on ##java asked "how to printTrackstrace to String," and got an answer of "e.getStackTrace() and concatenate each StackTraceElement." Yeeeick. There not only has to be a better way, but there is a better way.

If you are industrious enough to read the JavaDoc for Throwable, you'll find the printStackTrace(PrintWriter). To print the stack trace to a String, all you'd have to do is create a StringWriter, wrap that in a PrintWriter, and... call that method.

Therefore, dummies:

StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(pw);

new Exception().printStackTrace(pw);

// sw.getBuffer().toString()
// gives you the exception stack trace in a String.
Stop asking questions like this.
Tags :



Add a comment Send a TrackBack