Checked Exceptions
Checked exceptions represent a defect that occurs outside
of the control of the
application, such as opening a file that doesn’t exist or connecting to a database
with invalid credentials. A method that throws a checked exception forces its
callers to establish an error-handling policy. Callers must either surround the
method in a try/catch block or add the exception
to its method declaration
to push the responsibility further up the call stack. Checked exceptions extend
the Exception class. Common checked exceptions include IOExceptions,
FileNotFoundExceptions
, and InterruptedExceptions.
Unchecked Exceptions vs Checked Exceptions
Checked exceptions have been a source of contention in the Java community
because they are frequently overused. The official documentation states:
“If
a client can reasonably be expected to recover from an exception, make it
a checked exception. If a client cannot do anything to recover from the
exception, make it an unchecked exception.” When in doubt, unchecked
exceptions are preferred because it allows clients to choose whether or not
an error-handling policy is appropriate.
Errors
An Error is thrown by the JVM to indicate that a fatal condition has occurred.
Errors extend
the Throwable class directly, which gives them the behavior
of unchecked exceptions. Common errors include OutOfMemoryErrors
or StackOverflowErrors.