我有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);
}
答案 0 :(得分:6)
负责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;
}
// ..
}
表示您无法调用构造函数public Throwable(String message, Throwable cause)
,然后在同一实例上调用initCause
。
我认为您的代码已调用public Throwable(String message, Throwable cause)
,将null
作为cause
传递,然后尝试调用initCause
不允许的内容。