How can I convert a stack trace to a string?

ripper234 picture ripper234 · Jul 19, 2009 · Viewed 626.9k times · Source

What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

Answer

Brian Agnew picture Brian Agnew · Jul 19, 2009

Use Throwable.printStackTrace(PrintWriter pw) to send the stack trace to an appropriate writer.

import java.io.StringWriter;
import java.io.PrintWriter;

// ...

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String sStackTrace = sw.toString(); // stack trace as a string
System.out.println(sStackTrace);