javaexceptiondesign-patternsinstanceof

Is it acceptable to rethrow Exception's cause?


Sometimes I would want to throw an exception with more information to the user, so they can easily see why the method failed.

My method would look like this:

public myPublicMethod(...) throws Exception1, Exception2 {
  try {
    doSomething(); // this throws OtherException
  }
  catch (OtherException e) {
    Exception cause = e.getCause()
    if (cause instanceof Exception1) {
      throw (Exception1) cause;
    }
    if (cause instanceof Exception2) {
      throw (Exception2) cause;
    }
    throw new IllegalStateException("some other type of exception occurred", cause);
  }
}

Is this design acceptable?


Solution

  • No, it is not a good practice because it removes the wrapper exception.

    The proper handling for exceptions is that you must wrap into another exception or handle another.

    So we must change our signature to

    public myPublicMethod(...) throws WrapperException {
      try {
        doSomething(); // this throws OtherException
      }
      catch (OtherException e) {
        throw new WrapperException(e);
      }
    }