j.doe j.doe - 1 month ago 14
Java Question

Difference between throwing new RuntimeException vs casting cause to RuntimeException

Is there a difference between

} catch (ExceptionType1 e) {
throw new RuntimeException(e);
}


and

} catch (ExceptionType1 e) {
throw (RuntimeException) e.getCause();
}


If there is a difference, what should I be checking for in ExceptionType1 to figure out which one is better?

Answer Source

There are a number of differences:

 throw new RuntimeException(e);

This wraps whatever exception e in a new RuntimeException, and throw this RunTimeException


On the other hand:

throw (RuntimeException) e.getCause();

This tries to cast the cause of whatever exception e to a RuntimeException. Main differences are:

  • You lose the detail of the original exception e, as you only attempt to throw its cause (which might be null)
  • The cause might not inherit from RuntimeException and may not be castable, in which case a ClassCastException will occur.