请参阅以下代码并解释输出行为.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
结果是返回Val:10.
Eclipse显示警告:finally block does not complete normally.
catch块中的return语句会发生什么?
在Java中,try {...} finally {...}对我来说有些不直观.如另一个问题所示,最终总是在Java中执行吗?,如果try块中有return语句,则在定义finally块时将忽略它.例如,功能
boolean test () {
try {
return true;
}
finally {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
总是会返回false.我的问题:这是为什么?这个由Java做出的设计决策背后有一个特定的哲学吗?我很感激任何见解,谢谢.
编辑:我特别感兴趣的是'为什么'Java认为可以违反我定义的语义.如果我在try块中'返回',那么该方法应该在那里返回.但是JVM决定忽略我的指令并从一个实际尚未到达的子程序返回.