好吧,我通过相关问题,我阅读了JDK 1.7的源代码,但我找不到答案.
在这个问题中,我想完全忽略fillInStackTrace.
从JDK 1.4 initCause()开始,添加了方法.例如,当您使用核心反射来调用该方法时,您会收到InvocationTargetException,其中包含具有目标异常的原因.
当我看到这个功能时,我也开始在这样的场景中使用它
try {
//contains some code that can throw new IOException();
}
catch(IOException e){
throw new RuntimeException(e);
}
Run Code Online (Sandbox Code Playgroud)
所以,我抓住了一个异常,我还没准备好在这里处理它并且我重新抛出新的异常,其中我有原始异常作为原因.在一些scenarious而不是RuntimeException,但我的自定义异常被使用,所以有时我也调用e.getCause(),以便在外部块中正确处理此异常.
这是JDK 1.7之前的情况.我应该何时何地使用addSuppressed()?我应该将上面的代码更改为
try {
//contains some code that can throw new IOException();
}
catch(IOException e){
RuntimeException re= new RuntimeException(e.getMessage());
re.addSuppressed(e);
throw re;
}
Run Code Online (Sandbox Code Playgroud)
作为奖励问题,为什么不addSuppressed()返回Throwable作为initCause()确实允许throw (RuntimeException)new RuntimeException().initCause(e);?例如,为什么我不能这样做?:
try {
//contains some code that can throw new IOException();
}
catch(IOException e){
throw …Run Code Online (Sandbox Code Playgroud)