在Java中快速终止子句

Gre*_*ers 5 java fault-tolerance exception

有没有办法从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
}
Run Code Online (Sandbox Code Playgroud)

或者忽略了一个例外,你唯一可以做的事情是什么?

在C++中,它甚至不允许您忽略其中一个异常,只调用terminate().大多数其他语言使用与java相同的规则.

Chr*_* B. 14

设置一个标志变量,然后在finally子句中检查它,如下所示:

boolean exceptionThrown = true;
try {
   mightThrowAnException();
   exceptionThrown = false;
} finally {
   if (exceptionThrown) {
      // Whatever you want to do
   }
}
Run Code Online (Sandbox Code Playgroud)


Out*_*mer 10

如果您发现自己这样做,那么您的设计可能会出现问题."最终"块的想法是,无论方法如何退出,您都希望完成某些操作.在我看来,你根本不需要finally块,应该只使用try-catch块:

try {
   doSomethingDangerous(); // can throw exception
   onSuccess();
} catch (Exception ex) {
   onFailure();
}
Run Code Online (Sandbox Code Playgroud)