Asdfasf

Wednesday, September 24, 2014

EJ-61 Exception Chaining: Throw Exceptions Appropriate to the Abstraction

Ref: Effective Java by Joshua Bloch

It is disconcerting when a method throws an exception that has no appropriate connection to the task that it performs. Higher layers should catch lower-level exceptions and in their place, throw exceptions that can be explained in terms of the higher-level abstraction. This idiom is known as exception translation:

// Exception Translation
try {
// Use lower-level abstraction to do our bidding
...
} catch(LowerLevelException e) {
throw new HigherLevelException(...);
}


 A special form of exception translation called exception chaining is appropriate in cases where the lower-level exception might be helpful to someone debugging the problem that caused the higher-level exception.

// Exception Chaining
try {
... // Use lower-level abstraction to do our bidding
} catch (LowerLevelException cause) {
throw new HigherLevelException(cause);
}

No comments: