Difference between Checked and Unchecked Exceptions

A checked exception must either be

  • caught within the method, or
  • declared to be thrown by the method

This is enforced (“checked”) by the compiler.

Example: Exception is a checked exception, so this does not compile:
class Example {
    void method() {
        throw"error: Exception must be caught or declared to be thrown" new Exception();
     }
}
Here a throws declaration has been added, so this does compile:
class Example {
    void method() throws Exception {
        throw new Exception();
    }
}
Here the exception is caught within the method, so this does compile:
class Example {
    void method() {
        try {
            throw new Exception();
        } catch (Exception e) {
            // ...
        }
    }
}

An unchecked exception does not have this requirement.

Example: RuntimeException is an unchecked exception, so this does compile:
class Example {
    void method() {                    // No throws declaration
        throw new RuntimeException();  // No try/catch
    }
}

Checked exceptions are often used as “alternative return values” for unpredictable errors from which client can recover. Unchecked exceptions are usually an indication of a programming error or other condition from which the client can’t be expected to recover.

Comments