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; } }
$ 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)
Java exception stack trace example. Example getting stack trace on an exception. How to get a stack trace in an exception handler.
Basic Try Catch
Basic Try Catch Finally
Catch Multiple Exceptions At Once
Chained Exceptions
Create Your Own Exception Class
Example Of A NullPointerException
Exception Matching
Get A Stack Trace Of An Exception
Handling Multiple Catch Clauses
Print Stack Trace
Propagating an Exception
Rethrowing Exceptions
Shutdown Hook
Throw an Exception
Try Block Where Finally Clause Does Not Run
Try Block Without Catch
Try With Resources Statement