What is the easiest way to convert the result of Throwable.getStackTrace()
to a string that depicts the stacktrace?
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
.