Skip to the workspace
Pebellslearn by building
Exception Handling  ›  Lesson

Checked and Unchecked Exceptions

Checked and Unchecked Exceptions 14 minChecked exceptions must be caught or declared with throws because they represent expected outside failures, while unchecked RuntimeExceptions usually signal bugs and are not enforced by the compiler.

java / Checked and Unchecked Exceptions

Explore each scene at your own pace.

01 · The rule

The rule

Checked and Unchecked Exceptions

Checked exceptions must be caught or declared with throws because they represent expected outside failures, while unchecked RuntimeExceptions usually signal bugs and are not enforced by the compiler.

Decide which failures require a declared handling strategy and which indicate other problems.

Brew Bar's program loads the day's menu from a file. One day the file is missing, and the program has to cope. Another day a developer calls a method on a null drink. Java treats these two failures very differently: the compiler forces you to plan for the first, but not the second.

The rule

Checked means the compiler makes you handle it or declare it.

All exceptions descend from Throwable, in three branches:

Throwable
├── Error                      serious JVM trouble: do not catch
│     └── OutOfMemoryError
└── Exception                  checked, except for one branch:
      ├── IOException           checked
      └── RuntimeException      unchecked
            ├── NullPointerException
            ├── IllegalArgumentException
            │     └── NumberFormatException
            └── ArithmeticException

Checked exceptions are every Exception that is not a RuntimeException. They stand for problems outside your program's control that a careful program should expect, such as a missing file or a dropped network connection. For these, the compiler insists on one of two things:

// Option 1: handle it here
String loadMenu(Path file) {
    try {
        return Files.readString(file);
    } catch (IOException e) {
        return "Menu unavailable";
    }
}

// Option 2: declare it, and let the caller decide
String loadMenu(Path file) throws IOException {
    return Files.readString(file);
}

The throws IOException clause is part of the method's contract. Anyone calling loadMenu now faces the same choice.

Unchecked exceptions are RuntimeException and its subclasses. They usually mean a bug in the code, such as a null where an object was expected or an index past the end. The compiler does not force you to catch them; the right fix is usually to correct the code.

Errors, such as OutOfMemoryError, signal that the JVM itself is in trouble. Ordinary programs should not try to catch them.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.