Java – “Can’t overwrite cause” when setting a cause on exception with a null cause

exceptionjava

I have a RuntimeException that has no cause (t.getCause() returns null). When my code runs t.initCause(exceptionToAttach), it gives me an IllegalStateException with the message "Can't overwrite cause".

I wouldn't have thought this was possible. The exceptionToAttach is simply a new RuntimeException(), which seems to have itself set as the cause for some reason.

Any ideas what's going on?

edit with some relevant code

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);
}

Best Solution

The code responsible for the IllegalStateException exception is this:

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;
    }
// ..
}

which means that you cannot invoke constructor public Throwable(String message, Throwable cause) and then on the same instance invoke initCause.

I think your code has invoked public Throwable(String message, Throwable cause), passed null as the cause and then tried to call initCause what is not allowed.