Skip to main content

Checked vs Unchecked Exceptions

In Java, exceptions are broadly classified into two categories: Checked Exceptions and Unchecked Exceptions. Understanding the difference is crucial for writing robust and compiler-friendly Java code.


1. Checked Exceptions

Checked exceptions are exceptions that are checked by the compiler at compile-time.

If a method throws a checked exception, the compiler forces the programmer to either:

  1. Handle the exception using a try-catch block.
  2. Declare the exception using the throws keyword in the method signature.

If neither of these is done, the code will not compile.

Characteristics

  • They represent conditions outside the immediate control of the program (e.g., I/O errors, network issues, database problems).
  • All classes that inherit from Exception except RuntimeException and its subclasses are checked exceptions.

Examples

  • IOException (e.g., trying to read a file that doesn't exist)
  • SQLException (e.g., database connection fails)
  • ClassNotFoundException

2. Unchecked Exceptions

Unchecked exceptions are exceptions that are not checked by the compiler at compile-time. They occur at runtime.

The compiler does not force the programmer to handle or declare unchecked exceptions. It is up to the programmer to write logical code to avoid them (e.g., checking if an object is null before using it).

Characteristics

  • They typically represent programming errors, logic flaws, or improper use of an API.
  • Classes that inherit from RuntimeException (and its subclasses) are unchecked exceptions.

Examples

  • NullPointerException (e.g., calling a method on a null reference)
  • ArithmeticException (e.g., dividing an integer by zero)
  • ArrayIndexOutOfBoundsException (e.g., accessing an invalid index in an array)

3. Errors

Errors are also unchecked by the compiler, but they are conceptually different from unchecked exceptions.

Characteristics

  • Errors indicate severe problems that a reasonable application should not try to catch.
  • They are derived from the Error class.
  • They are typically thrown by the JVM itself.

Examples

  • OutOfMemoryError
  • StackOverflowError

Quick Comparison

Here is a summary comparing the three categories:

FeatureChecked ExceptionsUnchecked ExceptionsErrors
Checked at Compile-Time?YesNo (Checked at Runtime)No (Checked at Runtime)
SuperclassExceptionRuntimeExceptionError
RecoveryRecoverableRecoverableIrrecoverable
CauseExternal conditions (Files, Network, DB)Programming flaws (Logic errors, bad inputs)Severe system or environment failures
Handling RequirementMandatory (try-catch or throws)OptionalShould not be handled

[!TIP] Best Practice: Use checked exceptions for recoverable conditions and unchecked exceptions for programming errors.