/** * This code is from the book: * Winder, R and Roberts, G (1998) * Developing Java Software * John Wiley & Sons. * It is copyright (c) 1997 Russel Winder * and Graham Roberts. */ //Declare two subclass of Exception to provide user //defined exception classes. These exceptions //must be dealt with explicitly. class MyException extends Exception{ MyException(String s){ super(s); } } class YourException extends Exception{ YourException(String s){ super(s); } } class l1Except4{//Exception3 //A dummy no parameter constructor public l1Except4(){ } //A constructor that throws an exception public l1Except4(int x) throws MyException{ throw new MyException("Constructor failed"); } //A method that can throw two different exceptions, //requiring the throws declaration to list both. public void h(int x) throws YourException, MyException{ if (x == 1) throw new YourException("Thrown in h"); else throw new MyException("Thrown in h"); } //This method calls h and can handle any MyException //exceptions it might throw. However, it cannot //catch any YourException exceptions and they will be //propagated upwards requiring a throws declaration public void g(int x) throws YourException{ try{ h(x); } catch (MyException e){ System.out.println("Caught exception in g"); System.out.println(e.getMessage()); } finally{ System.out.println("g finally"); } } //This method will handle any exception thrown by the //call to g and does not need a throws declaration. public void f(int x){ try{ g(x); } catch (Exception e){ System.out.println("Caught exception in f"); System.out.println(e.getMessage()); } } //The methods r,s and t below demonstrate that //an exception or type Error does not need to be //handled explicitly, so no throws declarations //are provided. public void r(){ throw new Error("Deliberate Error"); } public void s(){ r(); } //An Error exception can still be caught using //a try-catch block. public void t(){ try{ s(); } catch (Error e){ System.out.println("Caught exception in t"); System.out.println(e.getMessage()); } } public static void main(String[] args) throws Exception{ //Test the exception handling l1Except4 e3 = new l1Except4(); e3.f(1); e3.f(2); e3.t(); //The constructor taking an int argument will //generate an exception that can be caught. try{ l1Except4 e3b = new l1Except4(1); } catch (Exception e){ System.out.println(e.getMessage()); } //However, the new expression does not need to //appear in a try block. The exception thrown //by the constructor will cause the program //to terminate prematurely. l1Except4 e3c = new l1Except4(); } } /******** sample compilation & run ******* # javac l1Except4.java # java l1Except4 g finally Caught exception in f Thrown in h Caught exception in g Thrown in h g finally Caught exception in t Deliberate Error Constructor failed # ******************************************/