我尝试了以下代码段:
private Integer getnumber() {
Integer i = null;
try {
i = new Integer(5);
return i;
} catch(Exception e) {
return 0;
} finally {
i = new Integer(7);
}
}
此方法返回5而不是7。
为什么它返回5而不是7?
提前致谢。
答案 0 :(得分:3)
这是因为finally
的{{1}}块在try..catch..finally
内的代码完成后运行(无论成功与否);对于您的代码,这是try..catch
发生的时间。
由于此行为,return i
的值已经放入方法的返回变量中,然后再为其分配新值7。以下方法可行:
i
答案 1 :(得分:0)
您已在finally
中分配了值,在此之前您已返回try
最终总是执行代码,但您已经返回try
答案 2 :(得分:0)
这是因为return语句在finally
执行之前执行,而i
的值在执行return语句时为5。
要验证这一点,您可以执行此操作
private Integer getnumber(){
Integer i = null;
try{
i = new Integer(5);
return i;
}catch(Exception e){return 0;}
finally{
i = new Integer(7);
System.out.println(i);
}
}
打印7
,因为finally
块确实执行,但只是在return
语句之后。
答案 3 :(得分:0)
在finally
中您要分配值,但在try
块
答案 4 :(得分:0)
返回值为5
,因为在return
块执行之前发生了finally
。