Does a finally block always get executed in Java?(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 中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:finally 块是否总是在 Java 中执行?


基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01