3

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
3
  • @Andreas Obviously I did. The format looks nothing like the desired result. Do you want me to mention this explicitly in the question? Commented May 16, 2018 at 18:48
  • The format of StackTraceElement.toString() looks exactly like the each entry of printStackTrace(), following the at. Commented May 16, 2018 at 18:53
  • @Andreas You're right. I had missed this. I marked your answer as accepted. Commented May 16, 2018 at 18:54

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.