411 REFERENCE · Wikibooks
Introduction to Programming Languages/Checked exceptions
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Checked vs Unchecked Exceptions
This is one of the most important Java concepts.
Java divides exceptions into:
checked;
unchecked.
Unchecked Exceptions
These are:
RuntimeException;
Error;
subclasses of them.
The compiler does NOT force handling.
Example:ArithmeticException
Checked Exceptions
All other exceptions.
The compiler forces you to:
handle them;
OR declare them.
Example:void z() {
throw new OutOfGas();
}This does NOT compile.Because OutOfGas is checked.
Throws
We must declare:void z() throws OutOfGas {
throw new OutOfGas();
}
Intuition Behind throws
It means: “This method may throw this exception”.
Propagation
If one method calls another that throws a checked exception:
it must also handle it;
OR propagate it.
Advantage of Checked Exceptions
They work as:
verified documentation.
The compiler guarantees:
that nobody silently ignores the error.
Disadvantages
Many programmers consider them:
verbose;
tiring;
excessively bureaucratic.
That is why modern languages often avoid this model.