Skip to content

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

    Java / Exceptions and Generics

    The Whole Story

    The whole module retold as one story — no new facts, a fast revision of Exceptions and Generics.

    Extra: Revision3 min read

    When something goes wrong, Java pulls an alarm cord: it throws an exception object, the current method stops, and the alarm climbs the call stack until someone catches it — or the thread dies and prints a stack trace, read from the type and message down to the first line of your code (Ch 1). Supervisors say try this, catch that specific failure, and finally clean up no matter what — specific catches before general ones, never an empty catch, never a return inside finally (Ch 2).

    Trouble comes in three kinds: Errors like running out of memory that normal code shouldn't catch; checked exceptions for expected failures outside your control, which the compiler forces you to catch or declare with throws; and unchecked RuntimeExceptions that usually mean a bug or bad input (Ch 3). Anything holding an operating-system handle is closed automatically, in reverse order, by try-with-resources on any AutoCloseable (Ch 4). Your own exception classes carry clear names and data, low-level failures are wrapped with their cause, and good code fails fast, catches only where it can act, and never uses exceptions — about 25× slower here — for ordinary control flow (Ch 5).

    Unlabelled boxes let a fish into the shoe box, discovered only at run time; generics label the box so the compiler checks at the door and casts disappear (Ch 6). A blueprint with a blank — Box<T>, Pair<A, B>, <T> T first(List<T>) — works for any object type (Ch 7), and a bound like <T extends Comparable<T>> says what the blank must be able to do, so the code can call it (Ch 8). After checking, the labels are peeled off — type erasure — which is why List<String> and List<Integer> are one class at run time, and why new T(), generic arrays and List<int> are impossible (Ch 9). And because an apple basket isn't a fruit basket you can drop bananas into, generics are invariant; wildcards recover flexibility safely — Producers extends, Consumers super (Ch 10).

    Next, Big-O and Complexity gives you the language for how fast all this code runs.