简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM