我有一个RuntimeException
没有原因(t.getCause() returns null
).当我的代码运行时t.initCause(exceptionToAttach)
,它会给我一条IllegalStateException
消息"无法覆盖原因".
我不会想到这是可能的.exceptionToAttach只是一个新的RuntimeException()
,它似乎因某种原因而被设置为原因.
有什么想法发生了什么?
编辑一些相关的代码
public static void addCause(Throwable e, Throwable exceptionToAttach) {
// eff it, java won't let me do this right - causes will appear backwards sometimes (ie the rethrow will look like it came before the cause)
Throwable c = e;
while(true) {
if(c.getCause() == null) {
break;
}
//else
c = c.getCause(); // get cause here will most likely return null : ( - which means I can't do what I wanted to do
}
c.initCause(exceptionToAttach);
}
Run Code Online (Sandbox Code Playgroud)
负责该IllegalStateException
异常的代码是:
public class Throwable implements Serializable {
private Throwable cause = this;
public synchronized Throwable initCause(Throwable cause) {
if (this.cause != this)
throw new IllegalStateException("Can't overwrite cause");
if (cause == this)
throw new IllegalArgumentException("Self-causation not permitted");
this.cause = cause;
return this;
}
// ..
}
Run Code Online (Sandbox Code Playgroud)
这意味着你不能调用构造函数public Throwable(String message, Throwable cause)
然后在同一个实例上调用initCause
.
我认为您的代码已经调用public Throwable(String message, Throwable cause)
,null
作为传递cause
,然后尝试调用initCause
不允许的内容.