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

当前回答

是的,它将始终调用,但在一种情况下,当您使用System.exit()时,它不会调用

try{
//risky code
}catch(Exception e){
//exception handling code
}
finally(){
//It always execute but before this block if there is any statement like System.exit(0); then this block not execute.
}

其他回答

除其他响应外,重要的是要指出,“finally”有权通过try重写任何异常/返回值。。捕捉块。例如,以下代码返回12:

public static int getMonthsInYear() {
    try {
        return 10;
    }
    finally {
        return 12;
    }
}

类似地,以下方法不会引发异常:

public static int getMonthsInYear() {
    try {
        throw new RuntimeException();
    }
    finally {
        return 12;
    }
}

虽然以下方法确实抛出了它:

public static int getMonthsInYear() {
    try {
        return 12;          
    }
    finally {
        throw new RuntimeException();
    }
}

下面是凯文的回答。重要的是要知道,要返回的表达式在finally之前求值,即使在finally之后返回。

public static void main(String[] args) {
    System.out.println(Test.test());
}

public static int printX() {
    System.out.println("X");
    return 0;
}

public static int test() {
    try {
        return printX();
    }
    finally {
        System.out.println("finally trumps return... sort of");
        return 42;
    }
}

输出:

X
finally trumps return... sort of
42

try-catch-finally是使用异常处理案例的关键词。作为正常外植体

try {
     //code statements
     //exception thrown here
     //lines not reached if exception thrown
} catch (Exception e) {
    //lines reached only when exception is thrown
} finally {
    // always executed when the try block is exited
    //independent of an exception thrown or not
}

finally块阻止执行。。。

调用System.exit(0)时;如果JVM退出。JVM中的错误

无论异常处理与否,Finally块始终执行。如果在try块之前发生任何异常,那么Finally块将不会执行。

如果不处理异常,在终止程序之前,JVM将执行finally块。仅当程序的正常执行因以下原因而失败时,才会执行程序。。

通过导致导致进程中止的致命错误。由于内存损坏,程序终止。通过调用System.exit()如果程序进入无限循环。