考虑到这段代码,我能绝对确定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");
}
考虑到这段代码,我能绝对确定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");
}
当前回答
即使在try块中放入return语句,也始终执行finally块。finally块将在return语句之前执行。
其他回答
在两种独特的情况下,返回后不会调用finally块:如果首先调用System.exit(),或者JVM崩溃。
让我尽量用最简单的方式回答你的问题。
规则1:finally块始终运行(虽然有例外。但让我们坚持一段时间。)
规则2:当控件离开try或catch块时,finally块中的语句会运行。控制权的转移可能是正常执行、break、continue、goto或return语句的执行或异常传播的结果。
在返回语句的情况下(由于其标题),控件必须离开调用方法,因此调用相应try finally结构的finally块。return语句在finally块之后执行。
如果finally块中也有return语句,它肯定会覆盖try块中挂起的语句,因为它会清除调用堆栈。
您可以在此处找到更好的解释:http://msdn.microsoft.com/en-us/....这一概念在所有高级语言中基本相同。
示例代码:
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int test() {
try {
return 0;
}
finally {
System.out.println("something is printed");
}
}
输出:
something is printed.
0
除了最后替换try块中的返回之外,异常也是如此。引发异常的finally块将替换try块中引发的返回或异常。
尝试这段代码,您将了解finally块中的代码是在return语句之后执行的。
public class TestTryCatchFinally {
static int x = 0;
public static void main(String[] args){
System.out.println(f1() );
System.out.println(f2() );
}
public static int f1(){
try{
x = 1;
return x;
}finally{
x = 2;
}
}
public static int f2(){
return x;
}
}
是的,它会被呼叫。这就是拥有finally关键字的全部意义。如果跳出try/catch块可以跳过finally块,这与将System.out.println放在try/catch之外相同。