[JAVA] Item 73: Throw exceptions appropriate to the abstraction
73. Throw exceptions suitable for abstraction
- Exceptions thrown in the lower layers can be annoying because they don't seem to have much to do with the specific tasks being done in the upper layers. Also, exceptions created in the lower layers can affect the API implementation in the higher layers (** not very pinpointed **). In order to avoid this problem, the exception thrown in the lower layer may be caught and translated into the exception in the upper layer.
// Exception Translation
try {
... // Use lower-level abstraction to do our bidding
} catch (LowerLevelException e) {
throw new HigherLevelException(...);
}
- When translating exceptions from low-rise to high-rise, you should write the chaining-aware constructor as follows in order to retain the exception information in the low-rise.
// Exception Chaining
try {
... // Use lower-level abstraction to do our bidding
} catch (LowerLevelException cause) {
throw new HigherLevelException(cause);
}
- The best thing is to prevent exceptions from occurring in the lower layers in the first place, and consider validating the values of the parameters passed for that purpose.