Convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace

1k views Asked by At

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

2

There are 2 answers

1
ykaganovich On

If you don't have to start with getStackTrace, then it's easier to use printStackTrace than getStackTrace if all you want is the string representation.

String trace;
try(StringWriter sw = new StringWriter();
  PrintWriter pw = new PrintWriter(sw)) {
  t.printStackTrace(pw);
  pw.flush();
  trace = sw.toString();
}
0
Tim Biegeleisen On

You can iterate over the array of StackTraceElement objects and append them to a StringBuilder like this:

Throwable t;
StringBuilder result = new StringBuilder("Throwable stack trace:");
for (StackTraceElement element : t.getStackTrace()) {
    result.append(element);
    result.append(System.getProperty("line.separator"));
}

System.out.println(result.toString());   // print out the formatted stack trace