【问题标题】:How to correctly handle nested exception inside catch block如何正确处理 catch 块内的嵌套异常
【发布时间】:2021-03-16 13:14:51
【问题描述】:

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

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

【问题讨论】:

    标签: java exception try-catch try-catch-finally


    【解决方案1】:

    在 Java 7 中,作为 try-with-resources 工作的一部分,Throwable 类得到了扩展,支持 suppressed 异常,专门用于此类场景。 p>

    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)
    

    【讨论】:

      猜你喜欢
      • 2017-03-31
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多