Skip to content

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

    Java / Exceptions and Generics

    try, catch, finally

    A catch block handles exceptions of its type and all its subclasses (polymorphism, 03javaoop.md Ch 4).

    Chapter 2 of 103 min read

    The Plain Picture#

    A supervisor who says: "Try running this job. If the part-shortage alarm goes off, do this instead. And whatever happens, switch off the machine at the end."

    The Real Names#

    Java
    try {
        // code that might throw
    } catch (NumberFormatException e) {
        // runs only if a NumberFormatException (or subclass) was thrown in the try block
    } catch (IOException | IllegalStateException e) {
        // multi-catch: either type
        // ...
    } finally {
        // ALWAYS runs: after the try finishes, after a catch, even if a return happens
    }
    • A catch block handles exceptions of its type and all its subclasses (polymorphism, Object-Oriented Programming Ch 4).

    • Catch blocks are checked top to bottom; the first matching one runs. So put specific types before general ones — the compiler rejects a general catch (Exception e) placed before a specific one it would hide.

    • finally is for clean-up that must happen no matter what.

    Under the Hood#

    Java
    try {
        int[] a = new int[2];
        a[5] = 1;
    } catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
        System.out.println("caught: " + e.getClass().getSimpleName());
    } finally {
        System.out.println("finally runs");
    }
    // caught: ArrayIndexOutOfBoundsException
    // finally runs

    Does finally always run? Almost always: after normal completion, after a caught exception, after an uncaught one, even after return. The exceptions: System.exit() is called, the JVM crashes or is killed (SIGKILL — Operating Systems Ch 12), or the thread runs forever.

    The finally + return trap:

    Java
    static int weird() {
        try {
            return 1;
        } finally {
            return 2;
        } // overrides the try's return — and would also swallow any exception!
    }
    
    System.out.println(weird()); // 2

    Never return from finally. (The compiler even warns about it.)

    Gotchas

    • Swallowing exceptions — catch (Exception e) { } with an empty body — hides bugs completely. At minimum log it; usually rethrow or handle it properly.

    • Catching Exception too broadly catches bugs you didn't expect (like NullPointerExceptions) and treats them as the error you did. Catch what you can actually handle.

    Check yourself

    4 questions
    1

    Why must specific catch blocks come before general ones?

    Show answer

    The first matching block wins; a general one first would catch everything, making the specific one unreachable (the compiler rejects it).

    2

    When does finally not run?

    Show answer

    On System.exit, a JVM crash/kill, or if the try block never finishes.

    3

    What does weird() return and why is it dangerous?

    Show answer

    2 — the finally return overrides the try's; it would also discard any exception, hiding failures.

    4

    What's wrong with catch (Exception e) {}?

    Show answer

    It silently hides every failure, including bugs, so problems go unnoticed.