finally里面不要抛出异常

来源:互联网 发布:杜兰特 数据 编辑:程序博客网 时间:2024/05/16 06:58

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抛出的异常将丢失掉。



原创粉丝点击