考虑到这段代码,我能绝对确定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或catch代码时JVM退出,那么finally块可能不会执行。同样,如果执行try或catch代码的线程被中断或终止,那么即使整个应用程序继续运行,finally块也可能不会执行。

其他回答

除非由于JVM崩溃或调用System.exit(0)而导致程序异常终止,否则finally块将始终执行。

除此之外,finally块中返回的任何值都将覆盖finally块执行之前返回的值,因此在使用try finally时,请注意检查所有退出点。

是的,会的。无论try或catch块中发生什么,除非调用System.exit()或JVM崩溃。如果块中有任何return语句,finally将在该return语句之前执行。

因为除非调用System.exit()(否则线程崩溃),否则将始终调用finally块。

在两种独特的情况下,返回后不会调用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/....这一概念在所有高级语言中基本相同。

尝试这段代码,您将了解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;
    }
}