所以我被分配去教授异常处理的 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/