本文介绍了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
try
orcatch
block - 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
finally
block is going to be executed by a daemon thread and all other non-daemon threads exit beforefinally
is called
这篇关于finally 块是否总是在 Java 中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!