Java Exceptions  «Prev 

Checked and Unchecked Exceptions in Java

In Java, checked exceptions are compile-time exceptions that must be explicitly handled using try-catch blocks or declared in the method signature with the `throws` keyword, ensuring developers address potential issues like `IOException` or `SQLException` before runtime. Unchecked exceptions, on the other hand, are runtime exceptions that extend `RuntimeException`, such as `NullPointerException` or `ArrayIndexOutOfBoundsException`, which do not require explicit handling and can propagate up the call stack unchecked. This distinction promotes robust error handling for anticipated failures while allowing flexibility for unexpected programming errors.

Understanding Exception Types

In Java, every error condition is represented by an Exception object. Exceptions are divided into two main categories based on how the compiler and runtime handle them:

Checked and Unchecked Exception Hierarchy
Figure 2.8: Object → Throwable → Error / Exception → RuntimeException


Checked Exceptions

Checked exceptions represent conditions that a well-written program should anticipate and handle. They occur due to external factors beyond the program’s immediate control-such as I/O operations or invalid file paths.

Key Characteristics

public void readFile() throws IOException {
    Files.readAllLines(Path.of("data.txt"));
}

Or handle the exception directly:

public void readFile() {
    try {
        Files.readAllLines(Path.of("data.txt"));
    } catch (IOException e) {
        System.err.println("File could not be read: " + e.getMessage());
    }
}

Common Checked Exceptions

  1. IOException – Input/output operation failure.
  2. SQLException – Database access error.
  3. ParseException – String parsing failure.
  4. ClassNotFoundException – Requested class cannot be located.
  5. InstantiationException – Attempt to instantiate abstract class or interface.
  6. InterruptedException – Thread interrupted during blocking operation.
  7. ReflectiveOperationException – Base type for reflection-related exceptions (Java 7+).

Unchecked Exceptions (Runtime Exceptions)

Unchecked exceptions signal programming errors, such as invalid logic or misuse of APIs. They extend RuntimeException and are not required to be declared or caught.

Key Characteristics

public void processArray(int[] arr) {
    try {
        System.out.println(arr[5]); // May throw ArrayIndexOutOfBoundsException
    } catch (ArrayIndexOutOfBoundsException e) {
        System.err.println("Array index is invalid: " + e.getMessage());
    }
}

Common Unchecked Exceptions

  1. ArithmeticException – Arithmetic error such as divide by zero.
  2. ArrayIndexOutOfBoundsException – Invalid array index.
  3. ClassCastException – Invalid object type cast.
  4. IllegalArgumentException – Invalid argument passed to a method.
  5. IllegalStateException – Method invoked at inappropriate time.
  6. NullPointerException – Null reference access.
  7. NumberFormatException – Invalid string-to-number conversion.
  8. UnsupportedOperationException – Attempted operation not supported.

Deciding Between Checked and Unchecked Exceptions

Guideline: If the caller can reasonably recover from the problem, use a checked exception. If recovery is impossible or indicates a programming mistake, use an unchecked exception.

For example, a database connection failure should throw a checked exception since retrying or notifying the user is possible. However, a NullPointerException or IllegalStateException usually indicates a logic flaw that should be corrected, not caught.

Hierarchy Summary

Java organizes exceptions under java.lang.Throwable:

Best Practices

Understanding checked versus unchecked exceptions allows developers to write clearer, more reliable Java code. When applied correctly, exception handling improves program stability, promotes early error detection, and simplifies debugging-making this one of the most important foundational topics in object-oriented Java programming.


SEMrush Software