Skip to content

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

    Java / Exceptions and Generics

    Quick Reference

    Glossary and cheat sheet for Exceptions and Generics — the page to reread before an interview.

    Extra: Reference5 min read

    Glossary#

    TermPlain meaningChapter
    exception / throwan error object interrupting execution / raising it1
    propagatethe exception moving up the call stack1
    stack tracethe list of calls active when it was thrown1
    try / catch / finallyprotected block / handler / always-run clean-up2
    multi-catchcatch (A | B e)2
    swallowingcatching and ignoring an exception2
    Throwable / Error / Exceptionroot / JVM-level problems / program-level problems3
    checked exceptionmust be caught or declared (IOException)3
    unchecked exceptionRuntimeException and subclasses (NullPointerException)3
    throw vs throwsthrow an object now / declare in a signature3
    resource / AutoCloseablemust be closed / interface with close()4
    try-with-resourcesautomatic closing in reverse order4
    suppressed exceptiona close() failure attached to the main one4
    custom exceptionyour own exception class5
    wrapping / cause / chainingtranslating while keeping the original ("Caused by")5
    fail fastreject bad input immediately5
    raw typegeneric type used without a type argument6
    generics / type parameterclasses/methods for any type / the T placeholder6, 7
    diamond <>inferred type arguments7
    generic methodstatic <T> ... with its own type parameter7
    bounded type<T extends X> restricting T8
    type erasuregeneric types removed after compile-time checking9
    reified / covariant (arrays)keep type at run time / String[] is an Object[]9
    ArrayStoreExceptionwrong type stored into an array at run time9
    invarianceList<Integer> is not a List<Number>10
    wildcard ? / ? extends / ? superunknown type / read-only producer / write consumer10
    PECSproducer extends, consumer super10

    Cheat Sheet#

    Exceptions

    Java
    try (var br = new BufferedReader(new FileReader(path))) {     // auto-closed
        ...
    } catch (FileNotFoundException e) {                           // specific first
        ...
    } catch (IOException e) {
        throw new QuizStorageException("could not load " + path, e);   // wrap WITH cause
    }
    Objects.requireNonNull(arg, "arg");  if (x < 0) throw new IllegalArgumentException("x < 0: " + x);
    Output
      checked: IOException, SQLException, InterruptedException      → catch or `throws`
      unchecked: NPE, IllegalArgument/State, IndexOutOfBounds, NumberFormat, ClassCast, Arithmetic
      never: empty catch · return in finally · exceptions for normal flow · wrap without cause

    Generics

    Java
    class Box<T> { T get(); }                     record Pair<A, B>(A first, B second) {}
    static <T> T first(List<T> xs)                static <T extends Comparable<T>> T maxOf(List<T> xs)
    double sum(List<? extends Number> src)        void fill(List<? super Integer> dst)       // PECS
    Output
      can't: new T() · new T[] · instanceof List<String> · List<int> · overload by type argument
      List<Integer> ≠ List<Number> (invariant) · arrays covariant → ArrayStoreException

    Try This Yourself#

    1. Read five stack traces. Deliberately cause: a NullPointerException, an ArrayIndexOutOfBoundsException, a NumberFormatException, an ArithmeticException (1 / 0) and a ClassCastException. For each, point to the first line in your own code.

    2. Resources. Write a class implementing AutoCloseable whose close() also throws. Use it in try-with-resources where the body throws too. Print e.getMessage() and e.getSuppressed()[0].getMessage().

    3. Custom exception. Add QuizNotFoundException (unchecked) with a quizId field. Write findQuiz(String id) that throws it, and a caller that catches it and prints "Quiz doesn't exist".

    4. Generic utilities. Write static <T> void swap(T[] arr, int i, int j), static <K, V> Map<V, K> invert(Map<K, V> m), and static <T extends Comparable<T>> boolean isSorted(List<T> xs). Try calling isSorted with a list of a class that isn't Comparable and read the compile error.