How can I convert a stack trace to a string?

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

Leave a Comment