考虑到这段代码,我能绝对确定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或catch块中发生什么,除非调用System.exit()或JVM崩溃。如果块中有任何return语句,finally将在该return语句之前执行。
其他回答
因为无论你遇到什么情况,总要进行决赛。您没有异常,它仍然被调用,捕获异常,它仍被调用
是的,它会被呼叫。这就是拥有finally关键字的全部意义。如果跳出try/catch块可以跳过finally块,这与将System.out.println放在try/catch之外相同。
示例代码:
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
无论异常处理与否,Finally块始终执行。如果在try块之前发生任何异常,那么Finally块将不会执行。
是的,会的。无论try或catch块中发生什么,除非调用System.exit()或JVM崩溃。如果块中有任何return语句,finally将在该return语句之前执行。