Part 3 of 6 · 2 min read
Two kinds of exception
Recoverable conditions or programming errors.
Java has two main kinds of exception. A checked exception must be caught or declared, so the compiler forces the caller to think about it. An unchecked exception (a subclass of RuntimeException) needs no declaration.
EJ Item 70 gives the rule: use checked exceptions for conditions the caller can reasonably be expected to recover from, and runtime exceptions for programming errors. A violated precondition is a programming error, so it is unchecked. A room that someone else booked a moment ago is a normal outcome, and the caller can offer another room, so it is checked.
class RoomBusyException extends Exception {
private final String room; private final int hour;
RoomBusyException(String room, int hour) {
super("room " + room + " busy at " + hour);
this.room = room; this.hour = hour;
}
String room() { return room; }
int hour() { return hour; }
}
Calling book("A1", 9) when A1 is taken at 9 throws it. The message reads "room A1 busy at 9", and the caller can read room() and hour() to suggest another slot. EJ advises that a checked exception should carry the facts needed for recovery, so callers never parse the message text. Item 75 adds that the message should include the values that caused the failure.
EJ Item 71 warns against overuse. A checked exception forces every caller to catch or declare it, which is a burden when no real recovery exists. When recovery is unclear, EJ says to prefer an unchecked exception. EJ Item 69 adds that exceptions are for exceptional conditions only. Using one to end a loop, or as an ordinary return path, is slow and confusing.
CC chapter 7 agrees on the main point and adds a reason: exceptions are better than return codes. A return code must be checked after every call, and callers forget. Exceptions keep the normal path clean.
Checked exception
A checked exception is an exception that the compiler forces the caller to catch or declare, used for conditions the caller can recover from.
Example: RoomBusyException, after which the caller can offer another room.
Check yourself:
1. Why is a bad hours value unchecked and a busy room checked?
2. What should a checked exception carry besides a message?
3. Why is a return code worse than an exception?