class MyException extends Exception { } public class RethrowException { public static void main(String[] args) { try { M1(); } catch (Exception e) { System.out.println("main(): Caught " + e.toString()); } } public static void M1() throws MyException { try { M2(); } catch (Exception e) { System.out.println("M1(): Caught " + e.toString()); System.out.println("M1(): Rethrowing " + e.toString()); throw e; } } public static void M2() throws MyException { System.out.println("M2(): Throwing MyException..."); throw new MyException(); } }
$ java RethrowException M2(): Throwing MyException... M1(): Caught MyException M1(): Rethrowing MyException main(): Caught MyException
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