RSS Entries RSS
RSS Subscribe by Email

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() + ")");
  }

Share and Enjoy:
  • Add to favorites
  • HackerNews
  • DZone
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Slashdot
  • Digg
  • Google Bookmarks
  • Facebook

3 Comments »

  1. atreyu said,

    July 27, 2009 at 6:24 am

    Hey good “hack” thanks a lot for spread your wisdom

  2. 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();)

  3. 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.

RSS feed for comments on this post · TrackBack URL

Leave a Comment