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:
e
, as you only attempt to throw its cause (which might be null)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.