考虑到这一点的代码,我可以绝对肯定的是,finally块总是执行,不管something()是什么?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
Run Code Online (Sandbox Code Playgroud) 请参阅以下代码并解释输出行为.
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语句会发生什么?
类似的问题已被问到here。但这并没有提供答案。
try {
object = (Dev)Class.forName("Dev").newInstance();
} catch (Exception e)
{
throw new RuntimeException("Devis not available");
}
finally
{
return object;
}
Run Code Online (Sandbox Code Playgroud)
但finally块给出警告:
finally 块没有正常完成
但根据我的理解,finally块总是被执行并返回对象。为什么警告说它不会正常完成?