What is the difference between Exception Translation and Exception Chaining in Java?
According to Joshua Bloch in Effective Java -
Exception Translation
Higher layers should catch lower-level exceptions
and, in their place, throw exceptions that can be explained in terms of the
higher-level abstraction.
try {
// Use lower-level abstraction to do our bidding
...
} catch(LowerLevelException e) {
throw new HigherLevelException(...);
}
Exception Chaining
It is special form of exception translation.
In cases where the lower-level exception might be helpful to someone debugging
the problem that caused the higher-level exception. The lower-level exception (the cause) is passed to the higher-level exception, which provides an
accessor method (Throwable.getCause) to retrieve the lower-level exception:
try {
... // Use lower-level abstraction to do our bidding
} catch (LowerLevelException cause) {
throw new HigherLevelException(cause);
}
The higher-level exception’s constructor passes the cause to a chaining-aware superclass constructor, so it is ultimately passed to one of Throwable’s chainingaware constructors, such as Throwable(Throwable):
// Exception with chaining-aware constructor
class HigherLevelException extends Exception {
HigherLevelException(Throwable cause) {
super(cause);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With