博文传送门:点击我
运行结果和我想的不同的程序的代码如下:
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();
}
}
}
eclipose 实际运行的结果:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false
我设想的结果与我为什么会这么想:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false //回到 testEX1 中调用 testEx2()处,然后进入 catch 块
testEx1, catch exception //进入 catch 块因此应该输出这句话,但不知道为什么实际并没有输出
testEx1, finally; return value=false
testEx, catch exception
testEx, finally; return value=false
请问我的思考错在哪里呢?为什么不进入 catch 块?谢谢
1
p2pCoder 2018-03-24 14:43:11 +08:00 1
https://blog.csdn.net/p106786860/article/details/12080501
主要原因还是在于 testEx2()中有返回值,异常信息就重置了,就没有了 可以理解为本来 throw 的 Exception 在返回信息的栈顶 在 finally 中 return 之后,栈顶就被返回值占据了,这就捕获不到异常信息了 |