/**
* 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.
*/
class MyException extends Exception{
MyException(String s){
super(s);
}
}
class l1Except3{//Exception2
//This method deliberately throws an exception
//selected by the argument. Note that
//NullPointerException and InterruptedException
//are library exception classes.
//InterruptedException is a direct subclass of
//Exception NullPointerException is a subclass of
//RunTimeException which is a subclass of Exception.
public void g(int x) throws Exception{
switch (x){
case 1 :
throw new MyException("Method g failed");
case 2 :
throw new NullPointerException("Method g failed");
case 3 :
throw new InterruptedException("Method g failed");
default :
throw new Exception("Method g failed");
}
}
public void f(int x){
try{
if (x < 5){
g(x);
}
System.out.println
("Got past call to g without exception");
return;
}
catch (MyException e){
System.out.print("Caught MyException in Method f: ");
System.out.println(e.getMessage());
}
catch (Exception e){
System.out.print("Caught Exception in Method f: ");
System.out.println(e.getMessage());
}
finally{
System.out.println("Done with f");
}
}
public static void main(String[] args){
l1Except3 e2 = new l1Except3();
e2.f(1);
e2.f(2);
e2.f(3);
e2.f(4);
e2.f(5);
}
}
/******** sample compilation & run *******
# javac l1Except3.java
# java l1Except3
Caught MyException in Method f: Method g failed
Done with f
Caught Exception in Method f: Method g failed
Done with f
Caught Exception in Method f: Method g failed
Done with f
Caught Exception in Method f: Method g failed
Done with f
Got past call to g without exception
Done with f
#
******************************************/