您的位置:首页 > 编程语言 > Java开发

java 中 finally里面写了return 会发生什么?

2016-01-25 20:29 567 查看
boolean test() throws Exception {
boolean ret = true;
try {
int b = 12;
int c;
for (int i = 1; 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;
}

}


这是一种很不好的写法。

开始认为会输出

i=12

testEx2, catch exception

testEx2, finally; return value=false
但事实是

i =12

testEx2, finally; return value=false

原因是finally里写return  return会冲掉上边的return 并且干掉catch抛出的异常
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: