Skip to content

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

    Java / Exceptions and Generics

    What an Exception Is

    An exception is an object describing an error, which interrupts normal execution.

    Chapter 1 of 105 min read

    Start With the Problem#

    Two separate problems StudyBuddy hits constantly:

    1. Things fail. The quiz file is missing. A student types "abc" as an answer count. The database is down. A student asks the AI a question with only 1 credit left. What should the code do? Returning -1 for "failed" is easy to ignore and gets confused with real values (a score could be -1 after a penalty). Printing an error and carrying on leaves the program in a broken state. And if you open a file and an error happens halfway, who closes the file?

    2. You keep rewriting the same code for different types. A "box that holds one value" for strings, another for integers, another for students. A "find the maximum" method for ints, another for Strings. And Java's lists, before 2004, held plain Objects, so you could accidentally put a number into a list of names and only find out when the program crashed in production.

    Exceptions are Java's structured answer to the first problem. Generics are the answer to the second. They're in one file because both are about the compiler helping you catch mistakes.

    The Plain Picture#

    A factory assembly line. A worker finds a broken part. Instead of quietly passing it along (so a broken product ships), they pull an alarm cord. The line stops at that point, and the alarm travels up the chain of supervisors until someone who knows what to do handles it. If nobody does, the whole factory shuts down.

    The Real Names#

    • An exception is an object describing an error, which interrupts normal execution.

    • Throwing an exception = pulling the cord: throw new IllegalArgumentException("credits must be >= 0");

    • The exception propagates up the call stack (Java Basics Ch 7): the current method stops immediately, then its caller, then its caller's caller… until some method catches it (Ch 2).

    • If nothing catches it, the thread dies and Java prints a stack trace.

    Under the Hood — reading a stack trace#

    Java
    public class Trace {
        static int parseScore(String s) {
            return Integer.parseInt(s);
        } // line 2
    
        static int level3(String s) {
            return parseScore(s) * 10;
        } // line 3
    
        static int level2(String s) {
            return level3(s) + 1;
        } // line 4
    
        public static void main(String[] args) {
            System.out.println(level2("abc")); // line 6
        }
    }

    Real output:

    Output
    Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
    	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    	at java.base/java.lang.Integer.parseInt(Integer.java:662)
    	at java.base/java.lang.Integer.parseInt(Integer.java:778)
    	at Trace.parseScore(Trace.java:2)
    	at Trace.level3(Trace.java:3)
    	at Trace.level2(Trace.java:4)
    	at Trace.main(Trace.java:6)

    How to read it:

    1. First line: the exception type (NumberFormatException) and its message (For input string: "abc"). Often that's enough.

    2. The at lines are the call stack at the moment of the throw, most recent call first. Each is one stack frame.

    3. Skip the java.base/... lines (inside Java's library) and find the first line in your code — Trace.parseScore(Trace.java:2). That's where to look.

    4. The lines below it show how you got there: main → level2 → level3 → parseScore.

    The process exited with code 1 (Operating Systems Ch 12). In a web server, one request's uncaught exception doesn't kill the server — the framework catches it and returns a 500 (Networking 3: DNS, HTTP and HTTPS Ch 5) — but the stack trace goes to the logs, and reading it is your first debugging step.

    Check yourself

    3 questions
    1

    What happens to the rest of a method when an exception is thrown in it?

    Show answer

    It stops immediately; the exception propagates to the caller.

    2

    In a stack trace, which line do you look at first to find your bug?

    Show answer

    The first at line that's in your own code (after the type and message).

    3

    What happens if no method catches an exception?

    Show answer

    The thread ends and the stack trace is printed (for main, the program exits with an error code).