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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Exception Chaining | |
try { | |
... // Use lower-level abstraction to do our bidding | |
} catch (LowerLevelException cause) { | |
throw new HigherLevelException(cause); | |
} |
No comments:
Post a Comment