Skip to content

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

    Java / Exceptions and Generics

    Your Own Exceptions, and Good Practice

    A custom exception is a class that extends Exception (checked) or RuntimeException (unchecked), carrying a clear name and any extra

    Chapter 5 of 104 min read

    The Real Names#

    A custom exception is a class that extends Exception (checked) or RuntimeException (unchecked), carrying a clear name and any extra data the handler needs.

    Java
    class InsufficientCreditsException extends Exception {
        // checked: callers must plan for it
        private final int needed, available;
    
        InsufficientCreditsException(int needed, int available) {
            super("Need " + needed + " credits, have " + available); // the message
            this.needed = needed;
            this.available = available;
        }
    
        int shortBy() {
            return needed - available;
        } // extra data for the handler
    }
    
    static int credits = 3;
    
    static void askAi(int cost) throws InsufficientCreditsException {
        if (cost > credits) throw new InsufficientCreditsException(cost, credits);
        credits -= cost;
    }
    
    try {
        askAi(2);
        askAi(5);
    } catch (InsufficientCreditsException e) {
        System.out.println(e.getMessage() + " (short by " + e.shortBy() + ")");
    }
    // Need 5 credits, have 1 (short by 4)

    The handler can now show "Buy 4 more credits" instead of a generic error.

    Wrapping (chaining) exceptions#

    Low-level exceptions should be translated into ones that make sense at your level — keeping the original as the cause:

    Java
    class QuizStorageException extends RuntimeException {
        QuizStorageException(String msg, Throwable cause) {
            super(msg, cause);
        } // pass the cause along
    }
    
    static void loadQuiz(String path) {
        try {
            /* ... reading the file throws ... */ throw new FileNotFoundException(
                path + " (No such file or directory)"
            );
        } catch (IOException e) {
            throw new QuizStorageException("could not load quiz " + path, e);
        }
    }
    // could not load quiz biology.json | cause: java.io.FileNotFoundException: biology.json (No such file or directory)

    A stack trace of a wrapped exception prints both, with a Caused by: section — so the root cause is never lost. Never wrap without passing the cause.

    Good practice — the rules interviewers look for#

    1. Fail fast: check arguments at the start of a method and throw immediately (IllegalArgumentException, Objects.requireNonNull(x)), instead of failing mysteriously ten calls later.

    2. Don't use exceptions for normal control flow. They're slow — creating one captures the whole stack trace. Measured on this Mac:

      Output
      100,000 failed Integer.parseInt calls caught as exceptions:  101 ms
      100,000 equivalent up-front checks:                            4 ms

      Check first (if (s.isEmpty() || !Character.isDigit(...))) when failure is common and expected.

    3. Catch at the level that can do something useful: retry, use a default, show a message, or return an HTTP status. Everything else lets it propagate.

    4. Never swallow (Ch 2). Always keep the cause when wrapping.

    5. Include useful context in messages: which quiz, which student, what value — not just "error".

    6. Use the standard types when they fit: IllegalArgumentException (bad argument), IllegalStateException (object in the wrong state for this call), UnsupportedOperationException, NoSuchElementException.

    Check yourself

    4 questions
    1

    When would you make a custom exception checked vs unchecked?

    Show answer

    Checked for expected, recoverable conditions callers should plan for (insufficient credits); unchecked for programming errors or failures callers can't reasonably handle.

    2

    Why pass the original exception when wrapping?

    Show answer

    So the root cause and its stack trace are preserved (shown as "Caused by").

    3

    Why shouldn't exceptions be used for normal control flow?

    Show answer

    They're expensive (they capture the stack trace) and they obscure the normal logic; measured ~25× slower than a simple check here.

    4

    What does "fail fast" mean?

    Show answer

    Detect invalid input or state as early as possible and throw immediately, rather than failing confusingly later.