/* * This program demonstrates how exceptions can be caught which thrown from another method. It also demonstrates * how Exceptions are caught based on type and subtype. * * In this case, we have two catches, ArithmeticException and Exception, to see where a type of Exception will be caught. * Run this program using different values for a and b between 0 and 3 each. */ public class Exception3 { public static void main(String[] args) { int a=1, b=1; // change these and see what happens try{ method1(a); // method1 can throw an exception, in this case it will throw } // a NullPointerException and be caught in the 2nd catch block catch(ArithmeticException e) { System.out.println("exception is an ArithmeticException type"); // handle exception from method1 if it is an ArithmeticException } catch(Exception e) { // handle all other types of Exceptions System.out.println("exception is not an ArithmeticException type"); } method2(b); // method2 will throw an exception but will be caught within method2 } // rather than here public static void method1(int x) throws ArithmeticException,NullPointerException,Exception { // no try or catch blocks here, any Exception thrown terminates this method if(x==0) throw new ArithmeticException("x=0"); else if(x==1) throw new NullPointerException("x=1"); else if(x==2) throw new Exception("x=2"); else System.out.println("No exception thrown from method1"); } public static void method2(int x) { try // if an Exception is thrown, catch it in one of the following catch blocks { if(x==0) throw new ArithmeticException("x=0"); else if(x==1) throw new NullPointerException("x=1"); else if(x==2) throw new Exception("x=2"); else System.out.println("No exception thrown from method2"); } catch(ArithmeticException e) { System.out.println("ArithmeticException caught in method2 with " + e); } catch(Exception e) { // will catch the NullPointerException or the Exception System.out.println("Exception caught in method2 with " + e); } System.out.println("reached this point after the try-catch blocks"); } }