我有以下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个记录器。
答案 0 :(得分:5)
在重新抛出之前,可以通过方法ex1
将ex2
添加到addSuppressed
的禁止异常中。
快速代码示例:
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)