public class PropagateException { public static void main(String[] args) { M1(); } public static void M1() { System.out.println("M1 started"); M2(); System.out.println("M1 finished"); } public static void M2() { System.out.println("M2 started"); // The Exception thrown in M4() is handled here try { M3(); } catch (Exception e) { System.out.println("M2: " + e.toString() ); } System.out.println("M2 finished"); } public static void M3() { System.out.println("M3 started"); M4(); System.out.println("M3 finished"); } public static void M4() { System.out.println("M4 started"); int x = 10 / 0; // Should throw Exception System.out.println("M4 finished"); } }
$ java PropagateException M1 started M2 started M3 started M4 started M2: java.lang.ArithmeticException: / by zero M2 finished M1 finished
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