Easiest way to convert the result of Throwable.getStackTrace()
to a string that depicts the stacktrace?
Asked
Active
Viewed 871 times
0

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

gokul prasad
- 1
- 2
-
2Add codes and be clear what you have worked on ...also see my edit... – SID --- Choke_de_Code Jun 09 '15 at 05:02
-
@gokulprasad Please review the answers given below. – Tim Biegeleisen Jun 11 '15 at 02:07
2 Answers
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
-
I think you have to call the `toString()` method on the `StringWriter`, not on the `PrintWriter`. – JojOatXGME Apr 22 '22 at 13:17
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