今天学习大神的文章:深入理解java异常处理机制 学到一个有意思的知识点。如果在finally中使用return会吃掉catch中抛出的异常。
看例子:
-
public class TestException {
-
public TestException() {
-
}
-
-
boolean testEx() throws Exception {
-
boolean ret = true;
-
try {
-
ret = testEx1();
-
} catch (Exception e) {
-
System.out.println("testEx, catch exception");
-
ret = false;
-
throw e;
-
} finally {
-
System.out.println("testEx, finally; return value=" + ret);
-
return ret;
-
}
-
}
-
-
boolean testEx1() throws Exception {
-
boolean ret = true;
-
try {
-
ret = testEx2();
-
if (!ret) {
-
return false;
-
}
-
System.out.println("testEx1, at the end of try");
-
return ret;
-
} catch (Exception e) {
-
System.out.println("testEx1, catch exception");
-
ret = false;
-
throw e;
-
} finally {
-
System.out.println("testEx1, finally; return value=" + ret);
-
return ret;
-
}
-
}
-
-
boolean testEx2() throws Exception {
-
boolean ret = true;
-
try {
-
int b = 12;
-
int c;
-
for (int i = 2; i >= -2; i--) {
-
c = b / i;
-
System.out.println("i=" + i);
-
}
-
return true;
-
} catch (Exception e) {
-
System.out.println("testEx2, catch exception");
-
ret = false;
-
throw e;
-
} finally {
-
System.out.println("testEx2, finally; return value=" + ret);
-
return ret;
-
}
-
}
-
-
public static void main(String[] args) {
-
TestException testException1 = new TestException();
-
try {
-
testException1.testEx();
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
}
-
}
运行结果:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false
有点奇怪,下层方法抛出的异常竟然没有被捕获。
如果把return和throw放在一起,直接会提示错误。"Unreachable statement"(无法被执行).
然而finally却可以成功骗过编译器让两者并存(是不是可以算是编译器的一个小bug呢),结果是后执行的会覆盖前者。finally如果有return会覆盖catch里的throw,同样如果finally里有throw会覆盖catch里的return。
进而如果catch里和finally都有return finally中的return会覆盖catch中的。throw也是如此。
这样就好理解一些了,retrun和throw都是使程序跳出当前的方法,自然就是冲突的。如果非要跳出两次(只有在catch和finally里存在这种情况)那么后者会覆盖前者。
版权声明:本文为博主原创文章,未经博主允许不得转载。
finally中使用return会吃掉catch中抛出的异常
原文:http://blog.csdn.net/tiantiandjava/article/details/46777051