finally 块是否总是在 Java 中执行?
考虑到这段代码,我可以绝对确定 finally 块总是执行,无论 something() 是什么?p>
Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
推荐答案
是的,finally 会在 try 或 catch执行完后被调用code> 代码块.
Yes, finally will be called after the execution of the try or catch code blocks.
finally 唯一不会被调用的时间是:
The only times finally won't be called are:
- 如果你调用
System.exit() - 如果你调用
Runtime.getRuntime().halt(exitStatus) - 如果 JVM 先崩溃
- 如果 JVM 在
try或catch块中遇到无限循环(或其他一些不可中断、非终止的语句) - 如果操作系统强行终止JVM进程;例如,
kill -9 <pid>在 UNIX 上 - 如果主机系统死机;例如,电源故障、硬件错误、操作系统恐慌等
- 如果
finally块将由守护线程执行并且所有其他非守护线程在调用finally之前退出
- If you invoke
System.exit() - If you invoke
Runtime.getRuntime().halt(exitStatus) - If the JVM crashes first
- If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the
tryorcatchblock - If the OS forcibly terminates the JVM process; e.g.,
kill -9 <pid>on UNIX - If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
- If the
finallyblock is going to be executed by a daemon thread and all other non-daemon threads exit beforefinallyis called
相关文章