即使你抛出一个新的异常,finally块是否运行? [英] Does a finally block run even if you throw a new Exception?
问题描述
在这段代码中,即使执行了catch块并且抛出了第二个异常,
In this code will someVar
be set even if the catch block is executed and the second Exception is thrown?
public void someFunction() throws Exception {
try {
//CODE HERE
} catch (Exception e) {
Log.e(TAG, "", e);
throw new Exception(e);
} finally {
this.someVar= true;
}
}
推荐答案
是,finally块总是运行...除了:
Yes, the finally blocks always runs... except when:
- 运行try-catch-finally块的线程被杀死或中断
-
- 您使用
System.exit(0);
- 底层虚拟机在其他一些方式
- 底层硬件在某种程度上不可用
此外,如果您的finally块抛出一个未捕获的异常,那么之后什么都不会被执行(即异常将被抛出,就像在任何其他代码中)。发生这种情况的一个很常见的情况是 java.sql.Connection.close()
。
Additionally, if a method in your finally block throws an uncaught exception, then nothing after that will be executed (i.e. the exception will be thrown as it would in any other code). A very common case where this happens is java.sql.Connection.close()
.
除此之外,我猜测你使用的代码示例只是一个例子,但要注意把实际的逻辑放在finally块中。 finally块用于资源清理(关闭DB连接,释放文件句柄等),而不是用于必须运行的逻辑。如果它必须运行在try-catch块之前,远离可能会引发异常的东西,因为你的意图几乎肯定在功能上是一样的。
As an aside, I am guessing that the code sample you have used is merely an example, but be careful of putting actual logic inside a finally block. The finally block is intended for resource clean-up (closing DB connections, releasing file handles etc), not for must-run logic. If it must-run do it before the try-catch block, away from something that could throw an exception, as your intention is almost certainly functionally the same.
这篇关于即使你抛出一个新的异常,finally块是否运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!