Should I keep a reference to the original Exception in the top Exception if another Exception eats it?

Consider this custom Exception class:

public class CustomException extends Exception {

    private static final long serialVersionUID = 1L;

    public static final int EXCEPTION1 = 1;
    public static final int EXCEPTION2 = 2;
    public static final int EXCEPTION3 = 3;

    private int exceptionType;
    private Throwable guiltyException;

    public CustomException(String message, int type, Throwable cause){
        super(message);
        this.exceptionType = type;
        this.guiltyException = cause;
    }

    public int getExceptionType(){
        return this.exceptionType;
    }

    public Throwable getGuiltyException(){
        return this.guiltyException;
    }

}

And then assume there is somewhere a method such as this:

public SomeReturnType someMethod(SomeArgument argument) throws CustomException{
    try{
        someExceptionalMethodCall(); // Throws Exception1, Exception2, Exception3
    } catch (Exception1 e1) {
        throw new CustomException("Some info1", CustomException.EXCEPTION1, e1);
    } catch (Exception2 e2) {
        throw new CustomException("Some info2", CustomException.EXCEPTION2, e2);
    } catch (Exception3 e3) {
        throw new CustomException("Some info3", CustomException.EXCEPTION3, e3);
    }
}

Is storing the Throwable just meaningless overhead I could avoid by adjusting the super call to Exception in the constructor of CustomException? Like this:

public CustomException(String message, int type, Throwable cause){
    super(message, cause);
    this.exceptionType = type;
}

Then I could get rid of guiltyException and getGuiltyException.

Is there any point in storing the Throwable cause in the CustomException class itself?

Jon Skeet
people
quotationmark

No, there's no reason to store the cause yourself when Throwable already has that facility. Your class should only introduce extra information, not duplicate fields which already have a meaning.

Aside from anything else, I would expect to be able to call getCause() and retrieve the original exception - whereas in your original code, I'd have to know that it's a CustomException, and call getGuiltyException(). One symptom of this is that any general purpose code logging the error won't see the cause in your current version - whereas it will if you use the standard approach to exception chaining.

people

See more on this question at Stackoverflow