本文介绍了catch语句中的return语句的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请参阅以下代码并解释输出行为。
Please see the following code and explain the output behavior.
public class MyFinalTest {
public int doMethod(){
try{
throw new Exception();
}
catch(Exception ex){
return 5;
}
finally{
return 10;
}
}
public static void main(String[] args) {
MyFinalTest testEx = new MyFinalTest();
int rVal = testEx.doMethod();
System.out.println("The return Val : "+rVal);
}
}
结果是返回Val: 10。
The result is the return Val : 10.
Eclipse显示警告: finally块无法正常完成
。
Eclipse shows a warning: finally block does not complete normally
.
catch块中的return语句会发生什么?
What happens to the return statement in catch block ?
推荐答案
它被 finally ,因为 finally
在其他所有内容后执行。
It is overridden by the one in finally
, because finally
is executed after everything else.
这就是为什么,一个经验法则 - 永远不会从返回
。例如,Eclipse会显示该代码段的警告:finally块无法正常完成
That's why, a rule of thumb - never return from finally
. Eclipse, for example, shows a warnings for that snippet: "finally block does not complete normally"
这篇关于catch语句中的return语句的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!