What is the easiest way to convert the result of Throwable.getStackTrace()
to a string that depicts the stacktrace?
This should work:
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
Printing stack trace to string
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceUtils {
public static String stackTraceToString(StackTraceElement[] stackTrace) {
StringWriter sw = new StringWriter();
printStackTrace(stackTrace, new PrintWriter(sw));
return sw.toString();
}
public static void printStackTrace(StackTraceElement[] stackTrace, PrintWriter pw) {
for(StackTraceElement stackTraceEl : stackTrace) {
pw.println(stackTraceEl);
}
}
}
It's useful when you want to print the current thread stack trace without creating instance of Throwable
- but note that creating new Throwable
and getting stack trace from there is actually faster and cheaper than calling Thread.getStackTrace
.
With Java 8 Stream API you can do something like this:
Stream
.of(throwable.getStackTrace())
.map(StackTraceElement::toString)
.collect(Collectors.joining("\n"));
It will take array of stack trace elements, convert them to string and join into multiline string.
public static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
Print the stack trace to a PrintStream
, then convert it to a String
:
// ...
catch (Exception e)
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(out));
String str = new String(out.toByteArray());
System.out.println(str);
}
Code from Apache Commons Lang 3.4 (JavaDoc):
public static String getStackTrace(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
throwable.printStackTrace(pw);
return sw.getBuffer().toString();
}
The difference with the other answers is that it uses autoFlush
on the PrintWriter
.