我想写一个这样的代码:
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)
}
来自业务逻辑的异常是否能够在cleanUp中可能存在中断?是否有更好的方法可以忽略cleanUp中的所有可能异常?
答案 0 :(得分:0)
catch
块只会捕获对应的 Throwables
块中引发的try
。因此,在周围try
块中抛出的异常将被保留并在外部catch
块中捕获。
答案 1 :(得分:0)
是。您的例外情况将达到最后一次。然而,对于我来说,这个结构看起来很怪异,我想我甚至宁愿在代码中多次使用cleanUp()而不是3次尝试。
答案 2 :(得分:0)
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