Printing a Stack Trace anywhere in Java
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() + ")");
}
atreyu said,
July 27, 2009 at 6:24 am
Hey good “hack” thanks a lot for spread your wisdom
Melski said,
August 9, 2009 at 3:33 am
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();)
Ben said,
November 19, 2009 at 7:12 pm
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.