Sometimes it could be useful to get the current stack trace while a Java program is being executed.

As of my limited knowledge, I don't know a direct way to get the stack trace, but sometimes the solution is right in front of your eyes.

This code will print the stack trace at any point of your proram:

StackTraceElement[] elements = new Throwable().getStackTrace();
for (int i = 0; i < elements.length; i++)
System.out.println(elements[i]);


Or using for-each:

for (StackTraceElement element : new Throwable().getStackTrace())
System.out.println(element);


Or even simpler you can just call printStackTrace() if you only want to print the stack trace in standard error:

new Throwable().printStackTrace();

Note that we are not actualy throw a Throwable. We only create a Throwable object which contains the information we want.

One Comment

  1. Nikos Stivaktakis says:

    You can also get the stack-trace of a different thread (not only the current one) using method: Thread.getStackTrace()

    Note:
    new Throwable().getStackTrace()
    is the same as:
    Thread.getCurrent().getStackTrace()

Leave a Reply