2

我有一个RuntimeException没有原因的(t.getCause() returns null)。当我的代码运行t.initCause(exceptionToAttach)时,它会给我一条IllegalStateException消息“无法覆盖原因”。

我不会想到这是可能的。exceptionToAttach 只是一个 new 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);
}
4

1 回答 1

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

我认为您的代码已调用,作为 thepublic Throwable(String message, Throwable cause)传递,然后尝试调用不允许的内容。nullcauseinitCause

于 2013-05-07T21:42:28.103 回答