Java - checked vs unchecked exceptions

[Updated: May 5, 2017, Created: Sep 1, 2016]

Checked exceptions are compile time requirement to provide alternative behavior in case of exceptions scenarios. Checked exceptions are thrown (typically designed on the API level) to avoid some wrong application level operations, for example invalid user input or files access problems.

Unchecked exception are typically unrecoverable runtime failure due to developer's illegal operation or errors in program's logic or by some JVM failures like out of memory situations.

Handling Checked exceptions

If any method calls may throw the checked exceptions, we must use try/catch blocks or use throws clause in the methods declaration.

By using 'throws' in method/constructor signature, we let exceptions propagate outside. In that case, we defer the actual exception handling responsibility to the caller chain.

The use of 'throws' in the method signature is suitable when we want our API users to give the control to act on error situations rather than the API handles them. The exception, in the caller chain, are typically handled in the UI layer to show user a friendly message.

A clear difference between checked and unchecked exceptions

Throwable and any subclass of Throwable that is not a subclass of either RuntimeException or Error are regarded as checked exceptions.

RuntimeException and all subclasses are known to be unchecked exception.

Unchecked exception are not required to be handled

Unchecked exceptions can optionally be handled by the caller but that's not a compile time requirement.

The predefined unchecked exceptions are based on errors encountered by JVM. They are not meant to be thrown like checked exception using 'throw new AnUncheckedException()' statement.

Method should not use 'throws' with unchecked exceptions

A method/constructor should also not use 'throws' clause with unchecked exceptions to let them bubble up. They should be handled within the method or ideally they shouldn't happen at the first place if we do proper programmatic checking e.g. check like whether if a String contains integers or not before using the method: Integer.parseInt(..). This method might cause JVM to throw NumberFormatException. If we cannot possibly do some kind of pre-checking to avoid unchecked exceptions then we should use try/catch.

The conceptual originator of checked and unchecked exceptions

The originator or source of 'checked' exception is typically 'throw new someCheckedException();' statement written somewhere in a library/API layer, whereas, the source of 'unchecked' exception is some runtime unexpected situation. Typically, an unchecked exception is raised when JVM encounters an illegal operation, for example, some mathematical illegal operation, wrong formatting operations, class casts, or out of memory or other runtime failures.

See Also