0

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

Mike Laren
  • 8,028
  • 17
  • 51
  • 70

2 Answers2

1

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();
}
ykaganovich
  • 14,736
  • 8
  • 59
  • 96
0

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
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360