javacodex.com
Java Examples
Java Examples
memu home questions

Get A Stack Trace Of An Exception

Here is an example on how to print out a stack trace of an exception.

Source: (Example.java)

class Example {
 
  public static void main(String args[]) {
    try {
      method1();
    } catch (Throwable e) {
      System.out.println("Exception: " + e.getMessage());
 
      StackTraceElement stack[] = e.getStackTrace();
      System.out.println("Stack:");
      for (StackTraceElement s : stack) {
        System.out.println(s);
      }
    }
  }
 
  static void method1() {
    method2();
  }
 
  static void method2() {
    method3();
  }
 
  static void method3() {
    int x = 1 / 0;
  }
}
 
 

Output:

$ java Example
Exception: / by zero
Stack:
Example.method3(Example.java:26)
Example.method2(Example.java:22)
Example.method1(Example.java:18)
Example.main(Example.java:5)

Contact: javacodex@yahoo.com