Java 中的快速失败finally 子句
-
09-06-2019 - |
题
有没有办法从finally子句中检测到正在抛出异常?
请参阅下面的示例:
try {
// code that may or may not throw an exception
} finally {
SomeCleanupFunctionThatThrows();
// if currently executing an exception, exit the program,
// otherwise just let the exception thrown by the function
// above propagate
}
或者忽略其中一个例外是您唯一能做的事情?
在 C++ 中,它甚至不允许您忽略异常之一,而只是调用 Terminate()。大多数其他语言使用与 java 相同的规则。
解决方案
设置一个标志变量,然后在finally子句中检查它,如下所示:
boolean exceptionThrown = true;
try {
mightThrowAnException();
exceptionThrown = false;
} finally {
if (exceptionThrown) {
// Whatever you want to do
}
}
其他提示
如果您发现自己这样做,那么您的设计可能有问题。“finally”块的想法是,无论方法如何退出,您都希望完成某些操作。在我看来,你根本不需要finally块,而应该只使用try-catch块:
try {
doSomethingDangerous(); // can throw exception
onSuccess();
} catch (Exception ex) {
onFailure();
}
如果函数抛出异常并且您想捕获异常,则必须将函数包装在 try 块中,这是最安全的方法。所以在你的例子中:
try {
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) { //or catch whatever you want here
// exception handling code, or just ignore it
}
}
您的意思是您希望finally 块根据try 块是否成功完成而采取不同的行为吗?
如果是这样,你总是可以这样做:
boolean exceptionThrown = false;
try {
// ...
} catch(Throwable t) {
exceptionThrown = true;
// ...
} finally {
try {
SomeCleanupFunctionThatThrows();
} catch(Throwable t) {
if(exceptionThrown) ...
}
}
但这变得相当复杂......您可能需要考虑一种方法来重组您的代码,以使这样做变得不必要。
不,我不这么认为。catch 块将在finally 块之前运行完成。
try {
// code that may or may not throw an exception
} catch {
// catch block must exist.
finally {
SomeCleanupFunctionThatThrows();
// this portion is ran after catch block finishes
}
否则,您可以添加异常代码将使用的同步()对象,您可以在finally块中检查该对象,这将帮助您确定是否在单独的线程中运行异常。
不隶属于 StackOverflow