catch 块中的链异常

chain exception in catch block

我有以下 java 代码:

 public void someMethod(){

    try{

        // some code which generates Exception

    }catch(Exception ex1) {

        try{

                // The code inside this method can also throw some Exception
                myRollBackMethodForUndoingSomeChanges();

        }catch(Exception ex2){
            // I want to add inside `ex2` the history of `ex1` too
            // Surely , I cannot set cause of `ex2` as `ex1` as `ex2`
            // can be caused by it's own reasons.
            // I dont want `ex1` details to be lost if I just throw `ex2` from my method



        }
    }

}

怎么做?

编辑: 实际上,这发生在我的服务层中,我有用于日志记录的控制器建议。因此我不想在这里添加 2 个记录器。

您可以在 ex2 中通过方法 addSuppressedex1 添加到被抑制的异常中,然后再重新抛出它。

快速代码示例:

public static void main(final String[] args) {
    try {
        throw new IllegalArgumentException("Illegal Argument 1!");
    } catch (final RuntimeException ex1) {
        try {
            throw new IllegalStateException("Illegal State 2!");
        } catch (final RuntimeException ex2) {
            ex2.addSuppressed(ex1);
            throw ex2;
        }
    }
}

将产生异常输出:

Exception in thread "main" java.lang.IllegalStateException: Illegal State 2!
    at package.main(Main.java:26)
    Suppressed: java.lang.IllegalArgumentException: Illegal Argument 1!
        at package.main(Main.java:20)