嵌套的尝试块,最后有捕获



我想写这样的代码:

try {
try {
someStuffThatCausesBusinessExceptions();
} finally {
try {
cleanUp();
} catch (Exception e) {
// I don't really care
}
}
} catch (BusinessLogicException e) {
// work with exception
// cleaning up must be done by that point (or at least tried to)
}

业务逻辑中的异常能否在清理期间可能出现的中断中幸存下来?有没有更好的方法来忽略清理中所有可能的异常?

catch块只会捕获在其相应try块中抛出的Throwables。因此,您在周围的try块中抛出的异常将被保留并在外部catch块中捕获。

是的。您的异常将到达最后一个捕获。然而,这种结构对我来说似乎很奇怪,我想我什至更喜欢在该代码中不止一次使用 cleanUp(( 而不是进行 3 次尝试。

There are two cases-:
1. if excetpion occurs from  mehtod someStuffThatCausesBusinessExceptions only then it will be caught in your outer catch block.
2. if the methods someStuffThatCausesBusinessExceptions and cleanUp both throw exceptions then the exception thrown from try block is suppressed.
Yes!! there is better way.You can use try-with-resources statement.
Please refere to this link.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

相关内容

  • 没有找到相关文章

最新更新