Skip to content
C

Checked vs Unchecked Exceptions

Checked exceptions are problems the compiler forces you to handle (using try-catch or throws) before your code will even compile — like IOException. Unchecked exceptions are not checked by the compiler at compile-time;


1. What are Checked and Unchecked Exceptions?

Checked exceptions are problems the compiler forces you to handle (using try-catch or throws) before your code will even compile — like IOException. Unchecked exceptions are not checked by the compiler at compile-time; they usually represent programming mistakes, like ArithmeticException or NullPointerException.

2. Why is it used?

This distinction helps separate genuinely unpredictable, external problems (like a missing file) from avoidable programming bugs (like dividing by zero). Checked exceptions force careful handling for known risky operations.

3. Real-Life Example

Think of checked exceptions like mandatory safety checks before a flight — you cannot skip them; they are enforced beforehand. Unchecked exceptions are more like accidents from careless driving — not something the system forces you to plan for beforehand, but caused by an avoidable mistake.

4. Syntax

java
// Checked exception - must be declared or handled void readFile() throws IOException { } // Unchecked exception - compiler does not force handling int result = 10 / 0; // ArithmeticException, unchecked

5. Example Program

java
public class CheckedUncheckedDemo { public static void main(String[] args) { try { int result = 10 / 0; // unchecked - ArithmeticException } catch (ArithmeticException e) { System.out.println("Unchecked exception handled: " + e.getMessage()); } } }

Output:

Unchecked exception handled: / by zero

6. Key Points to Remember

  • Checked exceptions extend Exception (excluding RuntimeException); the compiler forces handling.
  • Unchecked exceptions extend RuntimeException; handling is optional, and the compiler doesn't complain if you skip it.
  • This checked vs unchecked distinction is one of the most frequently asked topics in Java interviews.