'Convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace [duplicate]

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



Solution 1:[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();
}

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tim Biegeleisen