samedi 7 mai 2022

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?

Aucun commentaire:

Enregistrer un commentaire