首页 > 解决方案 > 如何正确处理 catch 块内的嵌套异常

问题描述

我有以下代码,我试图了解如何正确处理 catch 块中的异常,以便抛出两个异常(mainExceptionanotherException),以防万一anotherException我们不丢失来自mainException. 代码也很难闻——这种try-catch用法是某种反模式吗?有没有更好/正确的方法来处理这种情况?

        try {
            -some code-
        } catch (RuntimeException mainException) {
            try {
                -another code-
            } catch (Exception anotherException) {
                throw anotherException;
            } finally {
                throw mainException;
            }
        }

标签: javaexceptiontry-catchtry-catch-finally

解决方案


在 Java 7 中,作为try-with-resources工作的一部分,Throwable该类得到了扩展,支持抑制异常,特别适用于这样的场景。

public static void main(String[] args) throws Exception {
    try {
        throw new RuntimeException("Foo");
    } catch (RuntimeException mainException) {
        try {
            throw new Exception("Bar");
        } catch (Exception anotherException) {
            mainException.addSuppressed(anotherException);
        }
        throw mainException;
    }
}

输出(堆栈跟踪)

Exception in thread "main" java.lang.RuntimeException: Foo
    at Test.main(Test.java:5)
    Suppressed: java.lang.Exception: Bar
        at Test.main(Test.java:8)

推荐阅读