Java Stack Trace as String

March 19, 2018

I wanted to output a Java exception stack trace inside some XML, so I needed to get the stack trace into a string. This can be done with:

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

References