Java catch块中的链异常

Java catch块中的链异常,java,exception-handling,Java,Exception Handling,我有以下java代码: public void someMethod(){ try{ // some code which generates Exception }catch(Exception ex1) { try{ // The code inside this method can also throw some Exception myRollBackMethod

我有以下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个记录器。

您可以通过方法
addsupprested
ex1
添加到
ex2
中被抑制的异常中,然后再重试

快速代码示例:

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)

您可以通过方法
addsupprested
ex1
添加到
ex2
中被抑制的异常中,然后再重试

快速代码示例:

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)

为什么不能直接抛出
ex2
,还有什么原因要抛出
ex1
?如果确实需要,您可以在
ex2
中添加一个附加属性
rootCause
,并在需要时使用
ex1
对其进行初始化。不要捕获运行时异常-它们表明您作为开发人员做了错事。相反,确定是什么导致代码在运行时中断并修复它。看,我已经编辑了这个问题。为什么你不能直接抛出
ex2
,你也有理由抛出
ex1
?如果确实需要,您可以在
ex2
中添加一个附加属性
rootCause
,并在需要时使用
ex1
对其进行初始化。不要捕获运行时异常-它们表明您作为开发人员做了错事。相反,确定是什么导致代码在运行时中断并修复它。看,我已经编辑了这个问题。