Printing a Stack Trace anywhere in Java
07/03/2009
You don’t need to catch an Exception in order to print a stack trace in Java. Sometimes they can be helpful for debugging and logging purposes. Here’s an example of how to print a stack trace at any moment:
new Exception().printStackTrace();
If you want more control over the output, you can build some code off the following:
System.out.println("Printing stack trace:");
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (int i = 1; i < elements.length; i++) {
StackTraceElement s = elements[i];
System.out.println("\tat " + s.getClassName() + "." + s.getMethodName()
+ "(" + s.getFileName() + ":" + s.getLineNumber() + ")");
}
Hey good “hack” thanks a lot for spread your wisdom
Call me lazy but whats wrong with chucking an exception and printing its stack trace?
new exception().printstacktrace();
(off the top of my head, but at worse try{throw new exception();}catch(Exception e){e.printstacktrace();)
Thanks Melski. Not sure why that wasn’t my first thought. Your method is much simpler, so I’ve updated the post with your suggestion.
Even shorter:
Thread.dumpStack();