Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Exceptions and Generics

    The Hierarchy: Checked vs Unchecked

    Error — serious JVM problems: out of memory (02operatingsystems.md Ch 5), stack overflow (02operatingsystems.md Ch 6). Don't

    Chapter 3 of 104 min readOften asked in interviews

    The Plain Picture#

    Three kinds of trouble on the factory floor:

    • The building is on fire. Nobody on the line can fix that. Evacuate. (Errors)

    • A supplier might not deliver — expected, outside your control, and you should have a plan. The company requires every manager to write down their plan. (Checked exceptions)

    • A worker installed the part upside down — a mistake in how the work was done. The fix is to do the work correctly, not to plan for it everywhere. (Unchecked exceptions)

    The Real Names#

                             Throwable
                     ┌───────────┴────────────┐
                   Error                   Exception
           (JVM-level, don't catch)            │
           OutOfMemoryError            ┌───────┴──────────────────────┐
           StackOverflowError      (checked)                   RuntimeException  (unchecked)
                                   IOException                  NullPointerException
                                   FileNotFoundException        IllegalArgumentException
                                   SQLException                 IllegalStateException
                                   InterruptedException         ArrayIndexOutOfBoundsException
                                                                NumberFormatException
                                                                ClassCastException
                                                                ArithmeticException (e.g. / by zero)
                                                                UnsupportedOperationException
    • Error — serious JVM problems: out of memory (Operating Systems Ch 5), stack overflow (Operating Systems Ch 6). Don't catch them in normal code.

    • Checked exceptions — every Exception that is not a RuntimeException. They represent expected failures outside the program's control (file missing, network down). The compiler forces you to handle them: either catch them, or declare them with throws in the method signature so your caller must deal with them.

    • Unchecked exceptions — RuntimeException and its subclasses. They usually signal bugs or invalid input (a null reference, a bad argument). The compiler doesn't force handling.

    Under the Hood#

    The compiler enforcing a checked exception:

    Java
    static void read() {
        new FileReader("x.txt");
    }
    Output
    error: unreported exception FileNotFoundException; must be caught or declared to be thrown

    Two ways to satisfy it:

    Java
    static void read() throws FileNotFoundException {
        // declare: "my caller must handle this"
        new FileReader("x.txt");
    }
    
    static void read() {
        try {
            new FileReader("x.txt");
        } catch (FileNotFoundException e) {
            /* handle: use a default quiz, show a message... */
        }
    }

    throw vs throws (a favourite quiz question):

    • throw is a statement that throws one exception object now: throw new IllegalStateException("...").

    • throws is part of a method signature listing the checked exceptions the method might throw: void read() throws IOException.

    The ongoing debate. Checked exceptions make failure part of the method's contract, which is good — but they also spread throws clauses through every layer and can't be used inside lambdas (Modern Java) easily. Most modern Java frameworks (Spring) and nearly every other language (Python, JavaScript, Kotlin, C#) use only unchecked exceptions. A common practice: catch checked exceptions at the low level and wrap them in a meaningful unchecked exception (Ch 5).

    Check yourself

    4 questions
    1

    Checked vs unchecked — how does the compiler treat each?

    Show answer

    Checked exceptions must be caught or declared with throws; unchecked ones (RuntimeException subclasses) don't have to be.

    2

    Is NullPointerException checked? IOException? OutOfMemoryError?

    Show answer

    Unchecked; checked; neither — it's an Error.

    3

    throw vs throws?

    Show answer

    throw throws an exception object; throws in a signature declares which checked exceptions a method may throw.

    4

    What two options does the compiler give you for a checked exception?

    Show answer

    Catch it, or declare it with throws.