Java – How to convert a stack trace to a string

javastack-tracetostring

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

Best Solution

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);