class Exception1 extends Exception{
public Exception1(){
super("This is Exception1");
}
}
class Exception2 extends Exception{
public Exception2(){
super("This is Exception2");
}
}
public class Test {
public static void main(String args[]){
try {
testMethod3();
} catch (Exception1 e) {
System.out.println(e.getMessage());
} catch (Exception2 e) {
System.out.println(e.getMessage());
}
}
public static void testMethod3() throws Exception1, Exception2{
try {
System.out.println("1");
testMethod1(1);
} catch (Exception1 e) {
System.out.println("2");
throw e;
}finally{
try {
System.out.println("3");
testMethod2(1);
} catch (Exception2 e) {
System.out.println("4");
throw e;
}
}
System.out.println("5");
}
public static void testMethod1(int i) throws Exception1{
if(i==1){
throw new Exception1();
}
}
public static void testMethod2(int i) throws Exception2{
if(i==1){
throw new Exception2();
}
}
}
finally裏面不要拋出異常,否則,假如catch語句也拋出了異常,那麼上面一層代碼只能收到finally裏面拋出的異常,而catch拋出的異常將丟失掉。