首页 > 解决方案 > finally 之后带有 catch 的嵌套 try 块

问题描述

我想写这样的代码:

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 中所有可能的异常?

标签: javatry-catch-finally

解决方案


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


推荐阅读