Thread.getStackTrace() returns StackTraceElement[]. How can I convert this to a String with the same format as Exception.printStackTrace() returns?
To clarify: I don't have an exception, only a thread. I want to display the thread's stack trace using the same format as exception stack traces.
asked May 16, 2018 at 18:34
Gili
90.9k109 gold badges417 silver badges731 bronze badges
1 Answer 1
It is super easy, you just have to print them, with whatever prefix you want.
To print same as printStackTrace(), the prefix would be "\tat ".
Proof
// Show printStackTrace() output
new RuntimeException().printStackTrace(System.out);
// Similar output using getStackTrace()
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
System.out.println("getStackTrace()");
for (int i = 1; i < stackTrace.length; i++)
System.out.println("\tat " + stackTrace[i]);
Output
java.lang.RuntimeException
at Test.main(Test.java:5)
getStackTrace()
at Test.main(Test.java:8)
Note how for loop skipped index 0, since that is the stack frame for getStackTrace() itself.
answered May 16, 2018 at 18:49
Andreas
160k13 gold badges164 silver badges261 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Gili
I wanted to get back a String, not output to stdout, but I get your point. Good catch piggybacking on
StackTraceElement.toString(). I didn't realize this had the correct format.lang-java
StackTraceElement.toString()looks exactly like the each entry ofprintStackTrace(), following theat.