Part 4 of 6 · 2 min read
Translate exceptions
Hide the layer below.
A booking service sits on top of a storage layer. If the store fails with a disk error, the caller of book should not receive a database exception. That would leak a detail of the layer below, and break callers when the storage changes.
EJ Item 73 gives the idiom: catch the lower-level exception and throw one that makes sense at the higher level. This is exception translation. When the original helps debugging, pass it as the cause, which EJ calls exception chaining.
class BookingFailedException extends RuntimeException {
BookingFailedException(String m, Throwable cause) { super(m, cause); }
}
void book(String room, int hour) throws RoomBusyException {
if (busy.contains(room + "@" + hour)) throw new RoomBusyException(room, hour);
try {
store.save(room + hour);
} catch (IllegalStateException e) {
throw new BookingFailedException("could not save booking", e);
}
count++;
}
When the store fails with "disk error", the caller sees BookingFailedException with the message "could not save booking". Its getCause().getMessage() still shows "disk error" for the logs. The caller deals in booking terms, and the debugging trail is kept.
EJ also warns against ignoring exceptions (Item 77). An empty catch block hides a failure. If an exception truly can be ignored, a comment should say why, and the variable should be named ignored. Do not use translation as an excuse to swallow errors.
CC adds a practical point: wrap a third-party API in one class that throws your own exceptions, so callers do not depend on the library's exception types. This is the adapter pattern (Level 4, module 6) applied to errors.
Check yourself:
1. What does the caller of book see when the store fails?
2. Where can the original "disk error" still be read?
3. What does EJ say about an empty catch block?