Java 中的快速失败finally 子句
有没有办法从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 相同的规则。
Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?
See the example below:
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
}
or is ignoring one of the exceptions the only thing you can do?
In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,我不这么认为。 catch 块将在finally 块之前运行完成。
否则,您可以添加异常代码将使用的synchronize() 对象,您可以在finally 块中检查该对象,这将帮助您确定是否在单独的线程中运行异常。
No I do not believe so. The catch block will run to completion before the finally block.
Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.
如果函数抛出异常并且您想捕获异常,则必须将函数包装在 try 块中,这是最安全的方法。 所以在你的例子中:
If a function throws and you want to catch the exception, you'll have to wrap the function in a try block, it's the safest way. So in your example:
您的意思是您希望finally 块根据try 块是否成功完成而采取不同的行为吗?
如果是这样,您总是可以这样做:
不过,这变得相当复杂......您可能需要考虑一种方法来重组您的代码,以使这样做不必要。
Do you mean you want the finally block to act differently depending on whether the try block completed successfully?
If so, you could always do something like:
That's getting pretty convoluted, though... you might want to think of a way to restructure your code to make doing this unnecessary.
设置一个标志变量,然后在finally子句中检查它,如下所示:
Set a flag variable, then check for it in the finally clause, like so:
如果您发现自己这样做,那么您的设计可能有问题。 “finally”块的想法是,无论方法如何退出,您都希望完成某些操作。 在我看来,你根本不需要finally块,而应该只使用try-catch块:
If you find yourself doing this, then you might have a problem with your design. The idea of a "finally" block is that you want something done regardless of how the method exits. Seems to me like you don't need a finally block at all, and should just use the try-catch blocks: