Gili
Gili

Reputation: 90033

How to convert a StackTraceElement[] to a String?

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.

Upvotes: 3

Views: 6919

Answers (1)

Andreas
Andreas

Reputation: 159114

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.

Upvotes: 5

Related Questions