黑马程序员技术交流社区
标题:
(求助)finally 中的 return 语句
[打印本页]
作者:
犹豫铅笔
时间:
2014-10-3 10:31
标题:
(求助)finally 中的 return 语句
本帖最后由 犹豫铅笔 于 2014-10-3 10:35 编辑
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, catch exception
testEx1, finally; return value=false
testEx, catch exception
testEx, finally; return value=false
--------------------------------------
可是实际
运行的结果是:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false
哪位前辈能帮我解释一下
作者:
北风
时间:
2014-10-3 11:13
首先说,前四行输出结果是没有问题的,想必你也是通过视频中的思路来分析得出的。结果有疑问的地方无非就是你预测的结果比实际结果多了两行。
我看着程序,自己在笔记本上画了下我认为的运行结果,和你描述的运行结果一样,因为我没有实际敲码验证,所以只说一下我的理解。
testEx2(),根据程序描述,既能够执行for循环打印出2,1.接着第三次就会出现i=0的情况,接着抛出异常,执行catch,打印输出,最后执行finally,打印输出,并且返回一个ret,此时ret为false。
因为是testEx1中ret调用了testEx2()方法,所以程序回到testEX1()中将返回的false赋值给ret,接着判断if语句,结果为true,执行return,因为是在try,catch,fainlly语句体内,所以返回前实际还执行了finally块内代码,打印输出,因为按照规则,finally里面的代码块是必须要执行的。在这个过程中,并没有报错,所以也就不会catch了。。相同的道理,testEx1()方法也返回ret的值为false,程序返回到testEx()方法中,同样的道理在testEx()方法中也是只打印输出finally代码块内的语句。
不知道我的理解对不对。
作者:
犹豫铅笔
时间:
2014-10-3 15:43
北风 发表于 2014-10-3 11:13
首先说,前四行输出结果是没有问题的,想必你也是通过视频中的思路来分析得出的。结果有疑问的地方无非就是 ...
你这样说我明白了一点,但是还有疑问。
testEx2( )中catch的语句块这个不可否认是执行了的,但是他throw 了 e, 这个e被程序是怎么处理的?
我的猜想:在catch中的throw 语句是不是在finally之后执行,如果是这样就可以解释了。
不敢确定我的猜想是不是正确,刚在网上早资料发现了这样一段话:
finally中使用return是一种很不好的编程风格,它会覆盖掉所有的其它返回,并且吃掉catch中抛出的异常。
照这句话的说法,上述问题就说的通了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2