Room 8 of 15 · about 25 minutes

Checked and unchecked exceptions

You have now written the line from room 6 twice without being told what it does. This room is the rule behind it, and it arrives after you have used the line rather than before.

Tasks checked0 of 3 XP earned on this path0

What this room checks you can do

Student can classify a given exception class as checked or unchecked by checking whether RuntimeException (or Error) appears in its parent chain, predict whether a method that throws it requires a throws clause, and identify the Bloch design intent (checked for recoverable, unchecked for programming errors).

Notes

Checked vs unchecked exceptions

Java is one of the few mainstream languages whose compiler enforces a rule about exceptions: every method that calls something that can throw a checked exception must either catch it or declare it on the method header with throws. Unchecked exceptions have no such requirement. The compiler enforces the rule mechanically (JLS §11.2: the handle-or-declare rule).

//  Checked: compile error without `throws` or `try`:
public static void readFile(final String name) throws FileNotFoundException {
    new Scanner(new File(name));    //  FileNotFoundException is checked
}

//  Unchecked: compiler is silent either way:
public static int divide(final int a, final int b) {
    return a / b;                   //  ArithmeticException is unchecked
}

The two categories map cleanly onto the class hierarchy:

  • Checked: subclass of Exception but NOT of RuntimeException. Examples: IOException, FileNotFoundException, SQLException, ParseException.
  • Unchecked: subclass of RuntimeException (or Error). Examples: NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException, ArithmeticException.

To classify a new exception: walk the parent chain. If RuntimeException appears, unchecked. Otherwise checked.

The design intent

Bloch Effective Java Item 70 articulates Java's intent:

  • Use checked for recoverable conditions: situations where the caller might reasonably want to handle the failure and try something else (e.g., re-prompt for a filename, fall back to a default config, retry an HTTP request).
  • Use unchecked for programming errors: situations where the caller violated a precondition the method documented (null where non-null required, index out of range, divide by zero).

The compiler enforcement reflects the intent. For checked exceptions, the caller is forced to acknowledge that recovery may be needed; the type system makes the failure path visible. For unchecked, the failure is the programmer's bug to fix in code, not a runtime branch to handle.

In practice, Java's checked-exception design is controversial: Bloch himself notes that checked exceptions can be over-used and that languages like C# and Kotlin (which have no checked-exception concept) work fine. CSCD 210 teaches the rule because the JDK enforces it; CSCD 211 revisits whether to throw checked or unchecked in new code.

The CS1 student-facing summary

For CSCD 210 purposes:

  • FileNotFoundException is the canonical checked exception. Every method that opens a file must throws it (or catch).
  • NullPointerException is the canonical unchecked exception. No throws needed; bug shows at runtime.
  • Integer.parseInt throws NumberFormatException (unchecked) on bad input: no throws required, but careful programs catch it for user-facing input.

The five exceptions CSCD 210 students meet are catalogued in the roster that follows.

In other languages

  • C#: no checked-exception concept. Every exception is what Java calls "unchecked." The XML documentation comments are the only signal of which exceptions a method may throw.
  • Python: also no checked-exception concept. PEP 484 type hints can document exceptions, but the compiler does not enforce them.
  • Kotlin: explicitly removed checked exceptions from the language even when interoperating with Java; calling a Java method that declares throws IOException does not force a Kotlin caller to handle it.
  • Swift: has a different mechanism: throws is part of the function type, and callers must use try syntax. Conceptually similar to Java's checked exceptions but more flexible.

Tasks

Do each one, then check the box. Checking a box is you saying you did it. You can uncheck a box if you check it by accident.

  1. trace
    Show the answer

    FileNotFoundException checked; NumberFormatException unchecked.

  2. trace
    Show the answer

    compiles fine; NumberFormatException is unchecked.

  3. write
    Show the answer

    public static int readFirstInt(final String filename) throws FileNotFoundException: the throws covers the Scanner constructor; the NumberFormatException-like risks from nextInt are unchecked.

Self check

Type what you think the answer is. Getting it wrong costs nothing and you can try as many times as you want.

Given a method that calls new Scanner(new File(name)) with no throws clause and no try, predict the compile result.

Practice, untimed

Open this whenever you want, before the tasks or after them. Nothing in this section is recorded and nothing here is timed.

  1. Identify a CSCD 210 lab task where catching FileNotFoundException is the right move (rather than throws).write
    Show the answer

    an interactive program that re-prompts the user when the filename is wrong.

Optional challenge

This one is optional. Do what the room says you can do, without opening any answers, then read the two traps below and check your work against them. Each trap is copied from the notes for this room.

Student can classify a given exception class as checked or unchecked by checking whether RuntimeException (or Error) appears in its parent chain, predict whether a method that throws it requires a throws clause, and identify the Bloch design intent (checked for recoverable, unchecked for programming errors).

How this room finishes

This room is done when all three tasks are checked and the self check is answered.