"Can't overwrite cause" when setting a cause on exception with a null cause

2013-05-08T05:28:06

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

Copyright License:
Author:「B T」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.
Link to:https://stackoverflow.com/questions/16428861/cant-overwrite-cause-when-setting-a-cause-on-exception-with-a-null-cause

About “"Can't overwrite cause" when setting a cause on exception with a null cause” questions

Copyright License:Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.