返回信息流public class Easy {
public static void main(String[] args) {
System.out.println(test());
}
public static int test(){
int a = 1;
try{
a = 2;
throw new RuntimeException();
}catch(Exception e){
a = 3;
System.out.println(a);
return a;
}finally{
a = 4;
System.out.println(a);
}
}
}
请问输出为什么是:
3
4
3//?
而不是
3
4
4
呢?
这是一条镜像帖。来源:北邮人论坛 / java / #45404同步于 2015/11/10
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
[问题]try-catch-finally问题
dongqing
2015/11/10镜像同步33 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
这里面的3说了这个情况..我特么也没看清楚 先转
http://www.cnblogs.com/lanxuezaipiao/p/3440471.html
嗯,先看看
【 在 icyfox 的大作中提到: 】
: 这里面的3说了这个情况..我特么也没看清楚 先转
: http://www.cnblogs.com/lanxuezaipiao/p/3440471.html
因为有finally的存在,所以catch里面的return a;的行为好像是“先求return的参数(就是a的值),然后执行finally里面的东西,然后把原先求出来的值返回,而不是finally修改以后的a的值”。
catch(...) {
a = 3;
int tmp = a;
do_whatever_finally_does;
return tmp;
}
换个例子也许就清楚了:
try {
...
} catch (...) {
a = 3;
return a * a;
} finally {
a = 4
}
这样,catch里面做的是
catch(...) {
a = 3;
int tmp = a * a; // == 9
do_whatever_finally_does;
// now a == 4, but we don't care
return tmp;
}
详细说明在这里: http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2 留意“If the catch block completes abruptly for reason R”这一部分。“返回”也算complete abruptly。那个返回值是“reason”的一部分。
return的锅?
【 在 dongqing (dongqing) 的大作中提到: 】
: public class Easy {
: public static void main(String[] args) {
: System.out.println(test());
: ...................
通过『我邮2.0』发布