Java NotesRohit’s interview study guide
Chapter 06

Exceptions

Java's exception hierarchy, checked versus unchecked exceptions, try/catch/finally, try-with-resources and suppressed exceptions, chaining and reading a stack trace, and the habits interviewers look for. Every example was run with Java 25 (Eclipse Temurin 25.0.5.1).

Try it yourself. For each example, make an empty folder, save every code box in it under the name in its caption, and type the $ lines of the Terminal box in that folder. Your output should match the page. Most examples are compact source files (a file with just a void main(), chapter 01), which import all of java.base automatically, so java.io, java.nio.file and java.util classes need no import lines.

6 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Checked and unchecked exceptions

Added

In JavaScript you can throw anything: an Error, a string, a number, undefined. TypeScript can't say what a function might throw, so catch (e) gives you unknown and you check e instanceof … yourself. Java only lets you throw objects of class Throwable or a subclass, and the class tells you what kind of problem it is. The hierarchy has four parts you need to know:

ClassChecked?ExamplesWhat it means
Throwable(root)anything that can be thrown
ErroruncheckedOutOfMemoryError, StackOverflowErrorthe JVM is in trouble; don't catch it
Exception (and subclasses that aren't RuntimeException)checkedIOException, SQLException, InterruptedExceptionsomething outside your code failed: a file, a network, a database
RuntimeExceptionuncheckedNullPointerException, IllegalArgumentException, IllegalStateException, ArithmeticExceptionusually a bug, or a rule your caller broke

Checked means the compiler checks it: a method that can throw a checked exception must either catch it or declare it with throws IOException in its signature, and then every caller faces the same choice. Unchecked exceptions (RuntimeException, Error and their subclasses) need neither. The mental model: a checked exception is part of the method's type, like its return type. String readConfig(String name) throws IOException says "you get a String, or an IOException you must deal with". The closest TypeScript picture is a function returning Result<string, IOError> that the compiler forces you to unwrap, except that Java does it with exceptions.

Checked exceptions were Java's original bet: failures you can't prevent (a missing file, a dropped connection) should be impossible to ignore. Twenty-five years later the industry mostly decided they cost more than they give: they leak implementation details up through every layer (throws SQLException on a controller method), and they don't work with lambdas (see Exception best practices). Modern libraries lean unchecked, and Spring is the clearest example: it translates SQLException into its own DataAccessException hierarchy, which extends RuntimeException, and Jackson 3 (the JSON library in Spring Boot 4) made JacksonException a RuntimeException where Jackson 2's extended IOException. (Both checked with javap on the JARs: Spring 7.1.0, jackson-core 3.1.8 and 2.20.0.)

Report.java
String readConfig(String name) {
    return Files.readString(Path.of(name));
}

void main() {
    IO.println(readConfig("config.txt"));
}
Terminal
$ java Report.java
Report.java:2: error: unreported exception IOException; must be caught or declared to be thrown
    return Files.readString(Path.of(name));
                           ^
1 error
error: compilation failed
Report.java
String readConfig(String name) throws IOException {
    return Files.readString(Path.of(name));
}

int parsePort(String text) {
    return Integer.parseInt(text);
}

void main() {
    try {
        IO.println(readConfig("config.txt"));
    } catch (IOException e) {
        IO.println("can't read config: " + e);
    }
    IO.println("port " + parsePort("8080"));
    IO.println("port " + parsePort("80a"));
}
Terminal
$ java Report.java
can't read config: java.nio.file.NoSuchFileException: config.txt
port 8080
Exception in thread "main" java.lang.NumberFormatException: For input string: "80a"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:565)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at Report.parsePort(Report.java:6)
	at Report.main(Report.java:16)
What’s happening
  1. Left: Files.readString is declared throws IOException, a checked exception. readConfig neither catches it nor declares it, so the compiler refuses: "unreported exception IOException; must be caught or declared to be thrown". Nothing runs.
  2. Right: readConfig now declares it (throws IOException), which moves the decision to its caller. main catches it, so the program compiles.
  3. There's no config.txt in the folder, so readString throws java.nio.file.NoSuchFileException, a subclass of IOException. The catch (IOException e) block matches it and prints the exception's toString(): its class name and message (the file name).
  4. parsePort calls Integer.parseInt, which can throw NumberFormatException. That's a RuntimeException, so parsePort needs no throws and main needs no catch: "8080" parses fine.
  5. "80a" doesn't parse. Nothing catches the NumberFormatException, so it escapes main, the JVM prints the stack trace and exits with status 1. The compiler let this through because it's unchecked: the compiler only forces you to think about checked exceptions.
Does this compile?
Java
void main() {
    try {
        IO.println("hello");
    } catch (IOException e) {
        IO.println("never");
    }
}
Show answer
Never.java
void main() {
    try {
        IO.println("hello");
    } catch (IOException e) {
        IO.println("never");
    }
}
Terminal
$ java Never.java
Never.java:4: error: exception IOException is never thrown in body of corresponding try statement
    } catch (IOException e) {
      ^
1 error
error: compilation failed
What’s happening
  1. No: the compiler knows IO.println can't throw a checked IOException, so a catch for it is dead code, and for checked exceptions that's an error: "exception IOException is never thrown in body of corresponding try statement".
  2. The same check is what makes throws declarations trustworthy: the compiler tracks exactly which checked exceptions each statement can throw.
  3. catch (Exception e) or catch (RuntimeException e) would compile, because those can also catch unchecked exceptions, which any code may throw.

#try, catch, finally and multi-catch

Added

A try statement has one try block, any number of catch blocks and an optional finally. Three rules cover almost every interview question:

  1. Catch blocks are tried top to bottom, and the first one whose type matches wins. So a subclass must come before its superclass; the other way round, the subclass block could never run, and the compiler rejects it.
  2. finally always runs: after the try block finishes normally, after a catch block, after a return, and when an exception passes through uncaught. Only stopping the JVM (System.exit, a crash) skips it.
  3. Multi-catch (Java 7) handles several unrelated types in one block: catch (NumberFormatException | NoSuchFileException e).

JavaScript has one catch per try and you branch inside it (if (e instanceof TypeError)); Java's typed catch blocks are that if chain written by the language. The mental model for finally: it's a doorway every path out of the try must walk through, including return and exceptions.

Ports.java
int parsePort(String text) {
    IO.println("  parsing " + text);
    try {
        int port = Integer.parseInt(text.strip());
        if (port < 1 || port > 65535) {
            throw new IllegalArgumentException("out of range: " + port);
        }
        return port;
    } catch (NumberFormatException e) {
        IO.println("  not a number");
        return -1;
    } catch (IllegalArgumentException e) {
        IO.println("  rejected, " + e.getMessage());
        return -1;
    } finally {
        IO.println("  finally");
    }
}

void main() {
    IO.println(parsePort(" 8080 "));
    IO.println(parsePort("http"));
    IO.println(parsePort("70000"));
    IO.println(parsePort(null));
}
Terminal
$ java Ports.java
  parsing  8080 
  finally
8080
  parsing http
  not a number
  finally
-1
  parsing 70000
  rejected, out of range: 70000
  finally
-1
  parsing null
  finally
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.strip()" because "<parameter1>" is null
	at Ports.parsePort(Ports.java:4)
	at Ports.main(Ports.java:24)
What’s happening
  1. " 8080 ": strip() removes the spaces, parseInt gives 8080, the range check passes and return port runs. Before the method actually returns, finally prints finally; then main prints 8080.
  2. "http": parseInt throws NumberFormatException. The catch blocks are tried in order and the first matches: it prints not a number and returns -1, and finally still runs before the method leaves.
  3. "70000" parses, but the method throws its own IllegalArgumentException. The first catch doesn't match; the second does and prints the message.
  4. The order of the two catch blocks matters: NumberFormatException is a subclass of IllegalArgumentException. If the IllegalArgumentException block came first, it would catch both, and the compiler would reject the second block as unreachable (the quiz below shows the error).
  5. null: text.strip() throws NullPointerException. No catch matches, finally still prints, and the exception leaves parsePort and main: stack trace, exit status 1. finally runs even when nothing catches the exception.
  6. The helpful NPE message (Java 14+) says "<parameter1>" rather than "text" because the source launcher compiles without debug information, so parameter names aren't in the class file. Maven compiles with debug information by default, so in a real project the message names the variable.
AdvancedMulti-catch and rethrowing

Multi-catch is for when two unrelated exceptions get the same handling. The alternatives can't be subclasses of each other (that would be redundant, and the compiler says so), and the variable is implicitly final.

Load.java
int load(String file) {
    try {
        return Integer.parseInt(Files.readString(Path.of(file)).strip());
    } catch (NumberFormatException | NoSuchFileException e) {
        IO.println("bad input (" + e.getClass().getSimpleName() + "), using default");
        return 10;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

void main() throws IOException {
    Files.writeString(Path.of("good.txt"), "42\n");
    Files.writeString(Path.of("bad.txt"), "forty-two\n");
    IO.println(load("good.txt"));
    IO.println(load("bad.txt"));
    IO.println(load("missing.txt"));
}
Terminal
$ java Load.java
42
bad input (NumberFormatException), using default
10
bad input (NoSuchFileException), using default
10
What’s happening
  1. main writes two files and declares throws IOException itself, which is fine for a small program: if writing fails, the program stops with a stack trace.
  2. good.txt holds 42, so load returns 42.
  3. bad.txt holds text: parseInt throws NumberFormatException, which the multi-catch handles; getSimpleName() shows which alternative it was.
  4. missing.txt doesn't exist: NoSuchFileException, same block, same default. One handler, two unrelated exception types.
  5. Any other IOException (a permissions problem, say) goes to the last block, which wraps it in UncheckedIOException (Java 8), the standard unchecked wrapper for I/O errors. The specific NoSuchFileException sits in the first block, before the general IOException, as rule 1 requires.
Advancedfinally that returns swallows exceptions

A return (or throw) inside finally replaces whatever was leaving the try: a return value or an exception. That's why returning from finally is a classic bug, and javac has a lint warning for it.

Swallow.java
int risky() {
    try {
        throw new IllegalStateException("database is down");
    } finally {
        return 0;
    }
}

void main() {
    IO.println("risky() returned " + risky());
}
Terminal
$ java Swallow.java
risky() returned 0
$ javac -Xlint:finally Swallow.java
Swallow.java:6: warning: [finally] finally clause cannot complete normally
    }
    ^
1 warning
What’s happening
  1. The try block throws IllegalStateException. On the way out, finally runs, and its return 0 completes the method normally: the exception is thrown away, with no trace anywhere.
  2. main prints risky() returned 0. In a real service, "database is down" just vanished.
  3. javac -Xlint:finally warns: "finally clause cannot complete normally". The class file is still written; it's a warning, not an error. The rule: finally is for cleanup, never for return or throw.
What does this print? (finally and return)
Java
int value() {
    try {
        return 1;
    } finally {
        return 2;
    }
}

int counter() {
    int x = 1;
    try {
        return x;
    } finally {
        x = 99;
    }
}

void main() {
    IO.println(value() + " " + counter());
}
Show answer
Finally.java
int value() {
    try {
        return 1;
    } finally {
        return 2;
    }
}

int counter() {
    int x = 1;
    try {
        return x;
    } finally {
        x = 99;
    }
}

void main() {
    IO.println(value() + " " + counter());
}
Terminal
$ java Finally.java
2 1
What’s happening
  1. In value(), return 1 starts to leave the method, but finally runs first and executes return 2, which replaces the pending return. Result 2.
  2. In counter(), return x evaluates x (1) and saves that value before finally runs. finally sets x = 99, but the saved value is already 1, and finally doesn't return anything itself. Result 1.
  3. So it prints 2 1. The difference: a return in finally wins; an assignment in finally can't change a value that was already computed. (If x were a mutable object such as a list, changes to the object in finally would be visible, because what's saved is the reference.)
Does this compile? (catch order)
Java
void main() {
    try {
        IO.println(Integer.parseInt("x"));
    } catch (IllegalArgumentException e) {
        IO.println("illegal argument");
    } catch (NumberFormatException e) {
        IO.println("not a number");
    }
}
Show answer
Order.java
void main() {
    try {
        IO.println(Integer.parseInt("x"));
    } catch (IllegalArgumentException e) {
        IO.println("illegal argument");
    } catch (NumberFormatException e) {
        IO.println("not a number");
    }
}
Terminal
$ java Order.java
Order.java:6: error: exception NumberFormatException has already been caught
    } catch (NumberFormatException e) {
      ^
1 error
error: compilation failed
What’s happening
  1. No. NumberFormatException extends IllegalArgumentException, so the first block already catches every NumberFormatException.
  2. The second block is unreachable, and the compiler says so: "exception NumberFormatException has already been caught".
  3. The fix is to put the more specific type first. Rule of thumb: order catch blocks from most specific to most general.

#try-with-resources

Added

Files, database connections, sockets and locks must be released even when something fails. In Java 6 you did that with finally, by hand, and it was easy to get wrong (the example below shows how). Java 7 added try-with-resources: declare the resources in parentheses after try, and Java closes them for you when the block ends, however it ends.

The shape is try (var in = Files.newBufferedReader(path); var out = Files.newBufferedWriter(copy)) { … }, and when the block ends, out.close() and then in.close() run for you. The rules: a resource must implement AutoCloseable (one method, close()); resources are closed in reverse order of opening; they're closed before any catch or finally block of the same statement runs; and if the body throws and close() throws too, the body's exception is the one you get, and the close() exception is attached to it as a suppressed exception instead of being lost.

The TypeScript equivalent is using (TypeScript 5.2, now in V8 and Node 24+): a using variable's [Symbol.dispose]() runs when the block exits, last declared first, and if a disposer throws while an error is in flight you get a SuppressedError. It's the same design. In plain JavaScript you write try/finally, which is where Java 6 was.

Resources.java
class Resource implements AutoCloseable {
    private final String name;
    private final boolean failOnClose;

    Resource(String name, boolean failOnClose) {
        this.name = name;
        this.failOnClose = failOnClose;
        IO.println("open " + name);
    }

    @Override
    public void close() {
        IO.println("close " + name);
        if (failOnClose) throw new IllegalStateException("close failed: " + name);
    }
}

void main() {
    try (var db = new Resource("db", false); var file = new Resource("file", true)) {
        IO.println("working");
        throw new RuntimeException("work failed");
    } catch (RuntimeException e) {
        IO.println("caught: " + e.getMessage());
        for (Throwable s : e.getSuppressed()) {
            IO.println("  suppressed: " + s.getMessage());
        }
    } finally {
        IO.println("finally");
    }
}
Terminal
$ java Resources.java
open db
open file
working
close file
close db
caught: work failed
  suppressed: close failed: file
finally
What’s happening
  1. The resources open left to right: open db, then open file. Then the body prints working and throws RuntimeException("work failed").
  2. Before any catch runs, Java closes the resources in reverse order: close file first. That close() throws IllegalStateException.
  3. Java doesn't let the close failure replace the original one. It calls addSuppressed on "work failed" and carries on closing: close db.
  4. Now the catch runs with the original exception: caught: work failed. getSuppressed() returns the attached close failure: suppressed: close failed: file.
  5. finally runs last. Order of events: open, open, body, close (reverse), catch, finally. A stack trace of e would also show the suppressed exception, under a Suppressed: line.
AdvancedWhy Java 6 code lost exceptions

This is the pattern from Java 6 codebases, and the bug it hides. When both the body and the cleanup fail, the exception from finally replaces the one from the body: you see "close failed" in the logs and never learn what actually went wrong.

OldStyle.java
class Connection {
    void query() { throw new IllegalStateException("query failed: syntax error"); }
    void close() { throw new IllegalStateException("close failed: connection reset"); }
}

void main() {
    Connection c = new Connection();
    try {
        c.query();
    } finally {
        c.close();
    }
}
Terminal
$ java OldStyle.java
Exception in thread "main" java.lang.IllegalStateException: close failed: connection reset
	at OldStyle$Connection.close(OldStyle.java:3)
	at OldStyle.main(OldStyle.java:11)
What’s happening
  1. c.query() throws "query failed: syntax error". On the way out, finally calls c.close().
  2. close() throws too. An exception thrown from finally replaces the one already propagating, so the query failure is simply gone.
  3. The stack trace shows only "close failed: connection reset", pointing at the finally line: the real cause, the syntax error, appears nowhere. Correct Java 6 code needed a nested try around close() and a null check, for every resource.
  4. try-with-resources fixes it: the body's exception wins and the close failure is kept as suppressed, as in the main example.
AdvancedExisting variables as resources (Java 9)

Since Java 9 the parentheses can name an existing variable instead of declaring one, as long as it's final or effectively final (never reassigned). It's handy when the resource was created earlier or passed in.

Reuse.java
import java.io.*;

public class Reuse {
    static void printFirstLine(BufferedReader in) throws IOException {
        try (in) {
            System.out.println("first line: " + in.readLine());
        }
        try {
            in.ready();
        } catch (IOException e) {
            System.out.println("after the block: " + e.getMessage());
        }
    }

    public static void main(String[] args) throws IOException {
        printFirstLine(new BufferedReader(new StringReader("alpha\nbeta")));
    }
}
Terminal
$ java Reuse.java
first line: alpha
after the block: Stream closed
$ javac --release 8 Reuse.java
warning: [options] source value 8 is obsolete and will be removed in a future release
warning: [options] target value 8 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
Reuse.java:5: error: variables in try-with-resources are not supported in -source 8
        try (in) {
               ^
  (use -source 9 or higher to enable variables in try-with-resources)
1 error
3 warnings
What’s happening
  1. try (in) uses the parameter in as the resource. It's never reassigned, so it's effectively final, which is what the rule needs.
  2. The body prints first line: alpha. When the block ends, in.close() runs.
  3. After that, in.ready() throws IOException with the message "Stream closed", proving the reader really was closed.
  4. Compiling for Java 8 fails, and javac names the version the feature needs: "variables in try-with-resources are not supported in -source 8 (use -source 9 or higher …)". The three warnings above it only say that targeting Java 8 is obsolete.
What does this print? (close order)
Java
record R(String name) implements AutoCloseable {
    R { IO.println("open " + name); }
    public void close() { IO.println("close " + name); }
}

void main() {
    try (var a = new R("a"); var b = new R("b")) {
        IO.println("body");
        return;
    } finally {
        IO.println("finally");
    }
}
Show answer
Order.java
record R(String name) implements AutoCloseable {
    R { IO.println("open " + name); }
    public void close() { IO.println("close " + name); }
}

void main() {
    try (var a = new R("a"); var b = new R("b")) {
        IO.println("body");
        return;
    } finally {
        IO.println("finally");
    }
}
Terminal
$ java Order.java
open a
open b
body
close b
close a
finally
What’s happening
  1. A record can implement AutoCloseable; its compact constructor (R { … }) prints open as each one is created: open a, open b.
  2. The body prints body and then returns. Returning is just another way out of the block, so the resources are still closed, in reverse: close b, close a.
  3. Only then does finally run: finally. Resources are closed before the statement's own catch and finally, which is why finally can't use them any more.

#Custom exceptions and chaining

Added

Domain exceptions name failures in your business language: OrderNotFoundException, InsufficientStockException. They make code read better (catch (InsufficientStockException e) says what you handle) and let an outer layer map each one to the right response, such as a 404 or a 409 in a REST API (chapter 13). Write them as small classes that extend RuntimeException (or Exception if you really want them checked), with a constructor that takes a message and one that also takes a cause.

The cause is how exceptions chain. When a low-level failure (a NumberFormatException, an SQLException) makes a high-level operation fail, you throw your own exception and pass the original in as its cause. Nothing is lost: the stack trace prints your exception first and then each cause under a Caused by: line. JavaScript has the same idea since ES2022, new Error("import failed", { cause: err }), but Java has had it since 1.4, and every library uses it.

The mental model for reading a chained trace: the top line says what failed, the last Caused by: says why. When you're debugging, read the last Caused by: first.

Import.java
class OrderImportException extends RuntimeException {
    OrderImportException(String message, Throwable cause) {
        super(message, cause);
    }
}

record OrderLine(String sku, int quantity) {}

OrderLine parseLine(String line, int lineNumber) {
    String[] parts = line.split(",");
    try {
        return new OrderLine(parts[0], Integer.parseInt(parts[1]));
    } catch (NumberFormatException e) {
        throw new OrderImportException("line " + lineNumber + ": bad quantity in '" + line + "'", e);
    }
}

void main() {
    var lines = List.of("KB-1,2", "MS-7,ten", "HD-3,1");
    for (int i = 0; i < lines.size(); i++) {
        IO.println(parseLine(lines.get(i), i + 1));
    }
}
Terminal
$ javac Import.java
$ java Import
OrderLine[sku=KB-1, quantity=2]
Exception in thread "main" Import$OrderImportException: line 2: bad quantity in 'MS-7,ten'
	at Import.parseLine(Import.java:14)
	at Import.main(Import.java:21)
Caused by: java.lang.NumberFormatException: For input string: "ten"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:565)
	at java.base/java.lang.Integer.parseInt(Integer.java:662)
	at Import.parseLine(Import.java:12)
	... 1 more
What’s happening
  1. OrderImportException extends RuntimeException and passes message and cause to super(message, cause). That two-argument constructor exists on Throwable and every standard exception class.
  2. Line 1, KB-1,2, parses and prints as a record: OrderLine[sku=KB-1, quantity=2].
  3. Line 2, MS-7,ten: Integer.parseInt("ten") throws NumberFormatException. The catch turns it into an OrderImportException with a message in business terms (which line, what was wrong) and the original exception as the cause.
  4. This time the file is compiled with javac and run with java Import (a compact source file compiles to a class named after the file). Nothing catches the exception, so the JVM prints the chain. The first line is what failed ("line 2: bad quantity in 'MS-7,ten'") and where it was thrown (parseLine at line 14, called from main). Under Caused by: is why: NumberFormatException: For input string: "ten", with the frames inside Integer.parseInt and the call at line 12.
  5. The ... 1 more line means "the remaining frame is the same as in the exception above" (main at line 21), so Java doesn't print it twice. (Run with java Import.java instead, the source launcher's own frames appear at the bottom of the cause, which is why this example compiles first.)
  6. Line 3 never runs: an uncaught exception ends the program. The cause made the trace useful: without it you'd know line 2 was bad but not that "ten" was the problem.
AdvancedForgetting the cause

The most common chaining mistake is building the new exception from the old one's message and dropping the old exception itself. The trace then starts at your throw and the original stack is gone.

Lost.java
void load() {
    try {
        Files.readString(Path.of("/no/such/dir/settings.json"));
    } catch (IOException e) {
        throw new IllegalStateException("settings unavailable: " + e.getMessage());
    }
}

void main() {
    load();
}
Terminal
$ java Lost.java
Exception in thread "main" java.lang.IllegalStateException: settings unavailable: /no/such/dir/settings.json
	at Lost.load(Lost.java:5)
	at Lost.main(Lost.java:10)
What’s happening
  1. readString throws NoSuchFileException from deep inside the JDK's file system code.
  2. The catch copies only its message into a new IllegalStateException, and doesn't pass e as the cause.
  3. The trace shows the new exception, thrown at Lost.java:5, and no Caused by:: you can't tell it was a NoSuchFileException rather than a permissions error, or where in the JDK it happened.
  4. The fix is one argument: new IllegalStateException("settings unavailable", e). Then the full original trace appears under Caused by:.
AdvancedExceptions and records

An exception can't be a record: every record implicitly extends java.lang.Record, and Java has single inheritance, so it can't also extend RuntimeException. Use a small class with final fields when the handler needs data (an id, a status), not just a message.

Stock.java
class InsufficientStockException extends RuntimeException {
    private final String sku;
    private final int available;

    InsufficientStockException(String sku, int requested, int available) {
        super("only " + available + " of " + sku + " left, " + requested + " requested");
        this.sku = sku;
        this.available = available;
    }

    String sku() { return sku; }
    int available() { return available; }
}

void reserve(String sku, int quantity) {
    int inStock = 3;
    if (quantity > inStock) throw new InsufficientStockException(sku, quantity, inStock);
    IO.println("reserved " + quantity + " x " + sku);
}

void main() {
    reserve("KB-1", 2);
    try {
        reserve("KB-1", 5);
    } catch (InsufficientStockException e) {
        IO.println(e.getMessage());
        IO.println("offer the " + e.available() + " we have of " + e.sku());
    }
}
Terminal
$ java Stock.java
reserved 2 x KB-1
only 3 of KB-1 left, 5 requested
offer the 3 we have of KB-1
What’s happening
  1. InsufficientStockException builds a readable message for logs and keeps the facts as fields, so a handler doesn't have to parse the message.
  2. reserve("KB-1", 2) succeeds: reserved 2 x KB-1.
  3. reserve("KB-1", 5) throws. The catch prints the message, then uses e.available() and e.sku() to decide what to do next: offer the 3 that are left.
  4. In a REST API, the same fields would fill a 409 response's problem detail (chapter 13).

#Exception best practices

Added

Knowing the syntax is the easy part. What interviewers listen for is judgement, and it comes down to a few rules:

  • Don't swallow exceptions. An empty catch, or a catch that logs and returns null, turns a clear failure into a confusing one later.
  • Catch where you can act. Most code should let exceptions pass and have one place at the edge (a controller advice, a job runner, main) that logs them once and turns them into a response.
  • Translate at layer boundaries. A repository's SQLException shouldn't reach a controller. Wrap it (with the cause) in something the next layer understands, the way Spring's DataAccessException does for you.
  • Use exceptions for exceptional cases. "Not found" in a lookup is a normal outcome: return Optional (chapter 05). A broken invariant or an unavailable database is exceptional.
  • Never catch Throwable or Error in application code, and don't catch Exception except at that one edge.

The comparison with Node.js: there, a forgotten await or a missing .catch() gives an unhandled rejection that crashes the process (Node 15+) or vanishes, depending on configuration. Java's equivalents are a swallowed exception and an uncaught one in a background thread, which by default just prints a stack trace on that thread and ends it. The habits are the same in both: fail loudly, handle once, keep the cause.

Swallowed.java
record Config(int port) {}

Config load(String text) {
    try {
        return new Config(Integer.parseInt(text));
    } catch (NumberFormatException e) {
        return null; // "handled"
    }
}

void main() {
    Config config = load("80a");
    IO.println("loaded config");
    IO.println("starting on " + config.port());
}
Terminal
$ java Swallowed.java
loaded config
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Swallowed$Config.port()" because "<local1>" is null
	at Swallowed.main(Swallowed.java:14)
FailFast.java
record Config(int port) {}

class ConfigException extends RuntimeException {
    ConfigException(String message, Throwable cause) {
        super(message, cause);
    }
}

Config load(String text) {
    try {
        return new Config(Integer.parseInt(text));
    } catch (NumberFormatException e) {
        throw new ConfigException("server.port must be a number, got '" + text + "'", e);
    }
}

void main() {
    try {
        Config config = load("80a");
        IO.println("starting on " + config.port());
    } catch (ConfigException e) {
        IO.println("startup failed: " + e.getMessage());
        IO.println("cause: " + e.getCause());
    }
}
Terminal
$ java FailFast.java
startup failed: server.port must be a number, got '80a'
cause: java.lang.NumberFormatException: For input string: "80a"
What’s happening
  1. Left: load catches the NumberFormatException and returns null. The program happily prints loaded config, as if all were well.
  2. The failure surfaces one line later as a NullPointerException. The helpful NPE message says which variable was null (<local1> is config's slot number; with debug information, as Maven compiles, it says "config"), but not why it was null. In a real service that NPE can happen in another class, minutes later, far from the bad setting.
  3. Right: load translates the low-level exception into a ConfigException with a message that names the setting and the bad value, and keeps the original as the cause.
  4. main is the one place that handles it: startup failed: server.port must be a number, got '80a', and the cause still says exactly what the parser rejected.
  5. Same input, same failure, but the right side fails at the point of the mistake, with a message a person can act on.
AdvancedChecked exceptions inside lambdas

The standard functional interfaces (Function, Predicate, Consumer, chapter 08) declare no checked exceptions, so a lambda passed to map can't throw one. This is the main reason modern Java code avoids checked exceptions.

Sizes.java
void main() throws IOException {
    Files.writeString(Path.of("a.txt"), "alpha");
    Files.writeString(Path.of("b.txt"), "beta!");

    var sizes = Stream.of("a.txt", "b.txt")
            .map(name -> Files.size(Path.of(name)))
            .toList();
    IO.println(sizes);
}
Terminal
$ java Sizes.java
Sizes.java:6: error: unreported exception IOException; must be caught or declared to be thrown
            .map(name -> Files.size(Path.of(name)))
                                   ^
1 error
error: compilation failed
What’s happening
  1. Files.size declares throws IOException. The lambda name -> Files.size(…) is a Function<String, Long>, and Function.apply declares no exceptions.
  2. So the compiler rejects it: "unreported exception IOException; must be caught or declared to be thrown", pointing inside the lambda. main's own throws IOException doesn't help, because the lambda body is a different method (apply), called later by the stream.
  3. The usual fix is below: catch it inside the lambda and rethrow it unchecked.
Sizes.java
long sizeOf(String name) {
    try {
        return Files.size(Path.of(name));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

void main() throws IOException {
    Files.writeString(Path.of("a.txt"), "alpha");
    Files.writeString(Path.of("b.txt"), "beta!");

    IO.println(Stream.of("a.txt", "b.txt").map(this::sizeOf).toList());

    try {
        IO.println(Stream.of("a.txt", "nope.txt").map(this::sizeOf).toList());
    } catch (UncheckedIOException e) {
        IO.println("failed: " + e.getCause());
    }
}
Terminal
$ java Sizes.java
[5, 5]
failed: java.nio.file.NoSuchFileException: nope.txt
What’s happening
  1. sizeOf catches the checked IOException and rethrows it wrapped in UncheckedIOException, keeping it as the cause. Its signature has no throws, so this::sizeOf fits Function<String, Long>.
  2. The first stream reads both sizes: [5, 5] (alpha and beta! are five bytes each).
  3. The second stream hits nope.txt. UncheckedIOException travels out of the stream to the catch in main, and getCause() gives back the original NoSuchFileException.
  4. Extracting a small method like sizeOf keeps the stream readable; a try/catch written inside the lambda works too but makes the pipeline harder to scan.
AdvancedInterruptedException: restore the flag

InterruptedException is a checked exception thrown by blocking calls (Thread.sleep, BlockingQueue.take, Future.get) when another thread asks this one to stop. Throwing it clears the thread's interrupt flag, so if you catch it and carry on, the request to stop is lost. If you can't rethrow it, call Thread.currentThread().interrupt() to set the flag again.

Interrupt.java
void pause() {
    try {
        Thread.sleep(10_000);
    } catch (InterruptedException e) {
        IO.println("interrupted; flag after catch: " + Thread.currentThread().isInterrupted());
        Thread.currentThread().interrupt();
        IO.println("flag after interrupt(): " + Thread.currentThread().isInterrupted());
    }
}

void main() throws InterruptedException {
    Thread worker = new Thread(this::pause);
    worker.start();
    worker.interrupt();
    worker.join();
    IO.println("worker finished");
}
Terminal
$ java Interrupt.java
interrupted; flag after catch: false
flag after interrupt(): true
worker finished
What’s happening
  1. main starts a thread that sleeps for 10 seconds, then interrupts it straight away and waits for it with join().
  2. Whether the interrupt arrives before or during sleep, sleep throws InterruptedException at once (it checks the flag on entry), so the run doesn't wait 10 seconds.
  3. In the catch, the flag is already false: throwing the exception cleared it.
  4. interrupt() sets it again (true), so code further up (a loop checking isInterrupted(), an executor shutting down) still sees the request to stop. Chapter 09 covers threads properly.

#Your turn: exceptions

Added
Your turn: a quantity parser with a domain exception

Write parseQuantity(String text) that returns the number, and throws an unchecked InvalidQuantityException (keeping the original exception as the cause when there is one) if the text isn't a whole number or is not between 1 and 99. Print the results for "3", "0" and "lots".

Show answer
Quantity.java
class InvalidQuantityException extends RuntimeException {
    InvalidQuantityException(String message) {
        super(message);
    }

    InvalidQuantityException(String message, Throwable cause) {
        super(message, cause);
    }
}

int parseQuantity(String text) {
    int quantity;
    try {
        quantity = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        throw new InvalidQuantityException("not a whole number: '" + text + "'", e);
    }
    if (quantity < 1 || quantity > 99) {
        throw new InvalidQuantityException("must be 1 to 99, got " + quantity);
    }
    return quantity;
}

void main() {
    for (String text : List.of("3", "0", "lots")) {
        try {
            IO.println(text + " -> " + parseQuantity(text));
        } catch (InvalidQuantityException e) {
            IO.println(text + " -> rejected: " + e.getMessage() + (e.getCause() == null ? "" : " (cause: " + e.getCause().getClass().getSimpleName() + ")"));
        }
    }
}
Terminal
$ java Quantity.java
3 -> 3
0 -> rejected: must be 1 to 99, got 0
lots -> rejected: not a whole number: 'lots' (cause: NumberFormatException)
What’s happening
  1. Two constructors: one for a rule broken by your own check (no cause), one for wrapping a lower-level exception.
  2. "3" parses and passes the range check: 3 -> 3.
  3. "0" parses but fails the range check, so the exception has no cause.
  4. "lots" fails in parseInt; the catch wraps the NumberFormatException as the cause, which the handler shows by its simple name.
  5. The try covers only the parseInt call, not the range check: a narrow try makes it obvious which line can fail and why.
Your turn: a resource that times its work

Write an AutoCloseable class Step that prints start <name> when created and end <name> when closed. Use two of them in one try-with-resources, with a body that throws, and show that both still end, in reverse order, before the catch runs.

Show answer
Steps.java
class Step implements AutoCloseable {
    private final String name;

    Step(String name) {
        this.name = name;
        IO.println("start " + name);
    }

    @Override
    public void close() {
        IO.println("end " + name);
    }
}

void main() {
    try (var load = new Step("load"); var save = new Step("save")) {
        IO.println("doing the work");
        throw new IllegalStateException("disk full");
    } catch (IllegalStateException e) {
        IO.println("caught " + e.getMessage());
    }
}
Terminal
$ java Steps.java
start load
start save
doing the work
end save
end load
caught disk full
What’s happening
  1. close() overrides AutoCloseable.close() without throws Exception, so callers don't have to catch anything: an overriding method may declare fewer checked exceptions than the method it overrides.
  2. load then save start, the body prints and throws disk full.
  3. Java closes in reverse: end save, end load, and only then runs the catch: caught disk full.
Your turn: find the swallowed exception

This method sometimes "loses" errors. Explain why, and fix it so the exception reaches the caller and the cleanup message still prints.

Java
String fetch(boolean fail) {
    try {
        if (fail) throw new IllegalStateException("upstream timed out");
        return "data";
    } finally {
        IO.println("cleanup");
        return "default";
    }
}
Show answer

The return "default" inside finally replaces whatever was leaving the try, including the exception, so fetch(true) quietly returns "default". It also hides the real value: fetch(false) returns "default" too. Move the return out of finally:

Fetch.java
String fetch(boolean fail) {
    try {
        if (fail) throw new IllegalStateException("upstream timed out");
        return "data";
    } finally {
        IO.println("cleanup");
    }
}

void main() {
    IO.println(fetch(false));
    try {
        fetch(true);
    } catch (IllegalStateException e) {
        IO.println("caller saw: " + e.getMessage());
    }
}
Terminal
$ java Fetch.java
cleanup
data
cleanup
caller saw: upstream timed out
What’s happening
  1. fetch(false) returns "data"; finally prints cleanup on the way out, and main prints data.
  2. fetch(true) throws; finally prints cleanup and, with no return of its own, lets the exception continue.
  3. The caller's catch sees it: caller saw: upstream timed out. Cleanup still runs on both paths, which is all finally should do.

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.