Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Translation vs Exception Chaining in Java

Tags:

java

exception

What is the difference between Exception Translation and Exception Chaining in Java?

like image 638
vinS Avatar asked Aug 13 '26 01:08

vinS


1 Answers

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);
    }
}
like image 61
vinS Avatar answered Aug 15 '26 14:08

vinS