java - 在 Java 中阻止 Final block 执行的有效命令

标签 java exception try-catch-finally

所以我被分配去教授异常处理的 block ,但我遇到了一个我没有答案的问题。 Java 中哪些有效的(例如,不会导致编译器或运行时错误)命令会阻止finally block 执行?

一个return声明不会这样做,但是 System.exit(0)声明将。我的理解是,无论如何,finally block 都会执行。什么(有效)语句会阻止finally block 这样做,为什么?

最佳答案

引用Docs :

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

关于您关于System.exit()的示例,引用Docs再次

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

这意味着finally不会被执行。

简单的例子:

try {
    System.out.println("try");
    System.exit(0);
} finally {
    System.out.println("finally");
}

上面的例子只会打印try,但不会打印finally

关于java - 在 Java 中阻止 Final block 执行的有效命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33090914/

相关文章:

php - 关键字 'finally' 如何在 PHP 中使用?

python - 'finally' 是否总是在 Python 中执行?

java - 检索使用 ScheduledExecutorService 计划的任务实例

java - 在线程中调用创建线程的类中的方法

java - ClassNotFoundException : javax. wsdl.extensions.ExtensibilityElement 错误

java - 使用 Arrays.sort() 对并行数组进行排序

java - 为什么我的 @override for contains 不起作用?

.net - 为什么 .NET 异常是可变的?

java - 在 Spring Boot 中提供通用异常处理程序,将所有异常转换为 HTTP 500

java - “我无法正确捕获 NumberFormatException,因此我的 onClick 无法正常工作