Checked Exceptions
Checked exceptions represent failures a caller is required to acknowledge. They are Exception subclasses that do not extend RuntimeException.
A method must catch a checked exception or declare it with throws, passing responsibility to its caller. The compiler verifies that chain.
| Category | Compiler requirement | Example |
|---|---|---|
| Checked | Catch it or declare it with throws | IOException |
| Unchecked | No catch or declaration required | IllegalArgumentException |
Catch or declare
First define a checked exception for a missing score:
class MissingScoreException extends Exception {
MissingScoreException(String message) {
super(message);
}
}
A method declares that failure and throws it when the input is empty:
static int loadScore(String text) throws MissingScoreException {
if (text.isEmpty()) {
throw new MissingScoreException("score is missing");
}
return Integer.parseInt(text);
}
This method handles the failure at the point where it can choose a fallback:
static int requireScore(String text) {
try {
return loadScore(text);
} catch (MissingScoreException error) {
return 0;
}
}
This version leaves the decision to its caller:
static int requireScore(String text) throws MissingScoreException {
return loadScore(text);
}
Neither form is automatically better. A low-level helper often declares the exception. An application boundary may catch it to ask for another value or show an error.
Checked and unchecked are compiler categories. Either kind can still terminate a program when no caller handles it.
Catching is right when the method can recover or translate the failure. Declaring is right when the caller has the better recovery decision.
A throws clause documents possibility; it does not throw anything by itself.
Decide why the compiler requires this custom checked failure to be acknowledged below.