Does finally always execute in Java?
考虑到这个代码,我可以绝对确定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.");
}
Yes, finally
will be called.
The only times finally
won't be called are:
System.exit()
; try
or catch
block; Example code:
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int test() {
try {
return 0;
}
finally {
System.out.println("finally trumps return.");
}
}
Output:
finally trumps return.
0
Also, although it's bad practice, if there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false:
try { return true; } finally { return false; }
Same thing with throwing exceptions from the finally block.
链接地址: http://www.djcxy.com/p/2022.html上一篇: 直接投射vs'as'运营商?
下一篇: 最终总是在Java中执行?