Checked and unchecked exceptions

In Java, exceptions are broadly divided into three main categories, based on how the compiler and runtime handle them:


1. Checked Exceptions

  • Definition: Exceptions that are checked at compile-time.
  • If your code might throw a checked exception, you must either handle it with a try-catch block or declare it with throws.
  • These are typically recoverable situations.
  • Examples:
    • IOException
    • SQLException
    • ClassNotFoundException

Example code:

try {
    FileReader file = new FileReader("data.txt");
} catch (IOException e) {
    e.printStackTrace();
}

2. Unchecked Exceptions (Runtime Exceptions)

  • Definition: Exceptions that are not checked at compile-time — they occur at runtime.
  • Usually caused by programming errors like logic mistakes or improper use of APIs.
  • These extend RuntimeException.
  • Examples:
    • NullPointerException
    • ArrayIndexOutOfBoundsException
    • ArithmeticException

Example code:

int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException

3. Errors

  • Definition: Serious problems not intended to be caught by applications.
  • Usually caused by the JVM running out of resources or encountering critical issues.
  • These extend Error.
  • Examples:
    • OutOfMemoryError
    • StackOverflowError
    • VirtualMachineError

Example code:

public void recurseForever() {
    recurseForever(); // StackOverflowError
}

💡 Hierarchy Recap:

Throwable
 ├── Exception
 │    ├── Checked Exceptions
 │    └── Unchecked Exceptions (RuntimeException)
 └── Error

Leave a Reply