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抛出的异常将丢失掉。
本文探讨了Java中异常处理机制,特别是`try-catch-finally`块的使用及最终块内抛出异常的后果。
5598

被折叠的 条评论
为什么被折叠?



