问题
What is the difference between Exception Translation
and Exception Chaining
in Java?
回答1:
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);
}
}
来源:https://stackoverflow.com/questions/47806150/exception-translation-vs-exception-chaining-in-java