Easiest way to convert the result of Throwable.getStackTrace()
to a string that depicts the stacktrace?
Convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace
993 views Asked by gokul prasad At
2
There are 2 answers
0
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
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.