考虑到这段代码,我能绝对确定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");
}

当前回答

最后总是在结尾处调用

当您尝试时,它会执行一些代码,如果在尝试中发生了什么,那么catch将捕获该异常,您可以打印一些mssg或抛出错误,然后最后执行块。

Finally通常在执行清理时使用,例如,如果使用java中的扫描仪,则可能应该关闭扫描仪,因为它会导致其他问题,例如无法打开某些文件

其他回答

试用间苯二酚示例

static class IamAutoCloseable implements AutoCloseable {
    private final String name;
    IamAutoCloseable(String name) {
        this.name = name;
    }
    public void close() {
        System.out.println(name);
    }
}

@Test
public void withResourceFinally() {
    try (IamAutoCloseable closeable1 = new IamAutoCloseable("closeable1");
         IamAutoCloseable closeable2 = new IamAutoCloseable("closeable2")) {
        System.out.println("try");
    } finally {
        System.out.println("finally");
    }
}

测试输出:

try
closeable2
closeable1
finally

因为无论你遇到什么情况,总要进行决赛。您没有异常,它仍然被调用,捕获异常,它仍被调用

是的,它会被呼叫。这就是拥有finally关键字的全部意义。如果跳出try/catch块可以跳过finally块,这与将System.out.println放在try/catch之外相同。

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

在正常的执行过程中考虑这一点(即不抛出任何异常):如果方法不是“void”,那么它总是显式返回一些东西,然而,最终总是执行