Skip to content
notes.vinhnq.com

Search

Java CoreJunior16 min read

Java exceptions: checked vs unchecked, try-catch-finally and the call stack

Review 14 cards
On this page

Exceptions and error handling series: 1. Exceptions in Java · 2. Custom exceptions and error handling in Spring Boot

Every program runs into trouble: a missing file, a flaky network, bad input, a division by zero. This post covers the core Java side: the Throwable hierarchy, checked vs unchecked, throw/throws, try-catch-finally, try-with-resources, the path up the call stack, and what exceptions cost. Part 2 moves on to custom exceptions and Spring Boot: @RestControllerAdvice, ProblemDetail and DTO validation.

1. What an exception is

Key idea: an exception is an object describing something that went wrong at runtime. It separates detecting a problem from handling it.

Being an object, it has a class, state (message, cause, stack trace) and can be subclassed, so you can define your own. The basic flow:

  • The called method (callee) detects a problem, creates an exception and throws it with throw.
  • The calling method (caller) catches and handles it, or lets it keep going up.
  • Nobody catches it: it reaches the top of the stack, the JVM prints the stack trace and the thread stops (for a console app, the whole program dies).

The win: business code doesn’t get tangled with endless C-style if (errorCode != 0) checks. The detecting code usually doesn’t know whether to retry, tell the user or roll back; the handling code does.

2. The Throwable hierarchy

Key idea: everything throwable is a Throwable. Error means the JVM is in trouble (don’t catch it), Exception is something the app can handle, and RuntimeException is usually a bug.

flowchart LR
  Object --> Throwable
  Throwable --> Exception
  Throwable --> Error
  Exception --> IOException
  Exception --> SQLException
  Exception --> ClassNotFoundException
  Exception --> RuntimeException
  RuntimeException --> NullPointerException
  RuntimeException --> IllegalArgumentException
  RuntimeException --> ArithmeticException
  RuntimeException --> IndexOutOfBoundsException
  IllegalArgumentException --> NumberFormatException
  Error --> OutOfMemoryError
  Error --> StackOverflowError
  Error --> LinkageError
  • Throwable: the root; only Throwable and its subclasses can be used with throw.
  • Error: JVM or environment problems (OutOfMemoryError, StackOverflowError, NoClassDefFoundError). Applications generally should not catch these and try to “fix” them.
  • Exception: conditions an application can anticipate and handle.
  • RuntimeException: a subclass of Exception, usually a programming bug or a violated precondition.

Checked vs unchecked

Choosing checked or unchecked in application code (why checked exceptions spread throws through every layer, don’t mix with lambdas, and how to wrap a library’s exceptions at the boundary with their cause) is discussed in Clean code: error handling, boundaries and refactoring.

3. Throwing: throw and throws

Key idea: throw is a statement that throws an instance right now. throws is part of the method signature and lists the checked exceptions so callers know to handle them.

public class AccountService {

    // Checked: the caller must handle it or declare it too
    public String readStatement(Path file) throws IOException {
        return Files.readString(file);
    }

    // Unchecked: no declaration required, but document it in the Javadoc
    public void withdraw(Account account, long amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("amount must be positive, got " + amount);
        }
        if (account.balance() < amount) {
            throw new InsufficientBalanceException(account.id(), amount);
        }
        // ...
    }
}

The overriding rule: an overriding method can’t throw broader checked exceptions than the method it overrides. If an interface declares void run() with no throws, an implementation can’t throw IOException.

4. Catching: try-catch

Key idea: catch blocks are checked top to bottom and only the first matching handler runs. So subclasses must come before superclasses.

try {
    String content = Files.readString(path);
    int value = Integer.parseInt(content.trim());
    process(value);
} catch (NoSuchFileException e) {          // most specific first
    log.warn("Config file missing: {}", path);
} catch (NumberFormatException | IllegalStateException e) {  // multi-catch
    log.warn("Bad config content", e);
} catch (IOException e) {                   // more general later
    throw new UncheckedIOException(e);
}
  • Put catch (IOException) before catch (NoSuchFileException) and the compiler rejects it (“exception has already been caught”), because the second block is unreachable.
  • Multi-catch catch (A | B e): A and B must not be related by inheritance (compile error); e is effectively final.
  • Don’t want to handle it here? Let it propagate (and declare throws if it’s checked).

How exceptions travel up the call stack

main calls method1, which calls method2, which calls method3. Each level catches its own type (Ex1, Ex2, Ex3), and method3 throws:

sequenceDiagram
  participant M as main (catch Ex1)
  participant A as method1 (catch Ex2)
  participant B as method2 (catch Ex3)
  participant C as method3
  M->>A: call
  A->>B: call
  B->>C: call
  C--)B: throws
  Note over B: Is it Ex3? If so, handle it and continue after method2's try-catch
  B--)A: No match: method2's frame is popped, exception goes up
  Note over A: Is it Ex2? If so, handle it, and the rest of method2 never runs
  A--)M: No match: method1's frame is popped
  Note over M: Is it Ex1? If not, the thread dies and prints the stack trace
  • Ex3: method2 catches it. The rest of its try is skipped, but the code after its try-catch runs normally. method1 and main never learn anything happened.
  • Ex2: method2’s frame is discarded; method1 handles it and continues after its own try-catch.
  • Ex1: it goes all the way to main.
  • Nothing matches: the thread dies and the default UncaughtExceptionHandler prints the stack trace.
Inside the JVM: the exception table and stack unwinding

Every method has an exception table in its bytecode; each row holds a from..to instruction range, a target (where to jump) and a type. When an exception is thrown, the JVM looks up the current frame’s table. If no row matches, it pops the frame and checks the caller’s; this frame-by-frame peeling is called stack unwinding.

5. finally

Key idea: finally runs whether try finishes normally, throws, or returns halfway. Use it for cleanup; for resources, try-with-resources is better.

try {
    step1();
    step2();        // may throw
    step3();
} catch (BusinessException e) {
    recover();
} finally {
    cleanup();      // (*)
}
afterAll();         // (**)
Scenario step3 recover cleanup (*) afterAll (**)
No exception runs no runs runs
step2 throws BusinessException skipped runs runs runs
step2 throws something else (no matching catch) skipped no runs no: the exception goes to the caller
recover() itself throws runs no

“finally always runs” has its own exceptions: System.exit(), a JVM crash or kill -9, a thread stuck forever inside try, a daemon thread when the JVM shuts down.

A finally trap

try-with-resources (Java 7+)

6. When to use exceptions

Key idea: throw when a method can’t keep its contract and the caller has the context to decide. Catch where you can handle it; otherwise rethrow, always with the cause.

Wrap into a business exception and keep the cause so the stack trace stays whole:

try {
    paymentGateway.charge(order);
} catch (IOException e) {
    throw new PaymentUnavailableException("Gateway unreachable for order " + order.id(), e); // keep the cause
}

What not to do:

  • Use exceptions for normal control flow (e.g. catching NumberFormatException to test whether a string is numeric in a hot loop): creating one is expensive because fillInStackTrace() walks the whole stack.
  • Swallow exceptions: catch (Exception e) {} is how you get bugs that take a whole day to find. At minimum, log with the stack trace, or rethrow.
  • Throw a bare Exception (throw new Exception("Error")): callers are forced into catch (Exception e), which quietly catches real bugs too (NPEs, bad indexes). Throw a specific type (IllegalArgumentException, IllegalStateException) or a business exception.
  • Catch Throwable/Error, except at the outermost boundary (top-level handlers, frameworks).

If you catch InterruptedException and don’t rethrow, call Thread.currentThread().interrupt() to restore the interrupt flag.

Going deeper: cost and performance

Most of the cost is capturing the stack trace at construction, not the throw/catch itself. The deeper the stack (Spring + Hibernate easily hit 100+ frames), the more it costs.

Disabling stack traces and OmitStackTraceInFastThrow

For high-frequency business exceptions that don’t need a stack trace, use the Throwable(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) constructor with writableStackTrace = false.

Checked exceptions and lambdas

Function, Supplier and friends don’t declare throws, so a lambda can’t throw a checked exception. The fixes: wrap it in an unchecked exception (UncheckedIOException) inside the lambda, or define your own functional interface with throws. This is one reason Spring and Hibernate moved almost entirely to unchecked exceptions.

Exercises

Exercise 1: Fix the compile error

The task (paraphrased): a method takes an int and throws new Exception("...") when the value is below a threshold, with no declaration. Make it compile.

Solution to Exercise 1

Cause: Exception is checked, and the method throws it without catching it or declaring throws.

// Option 1: declare throws and push the responsibility to callers
public void check(int value) throws Exception {
    if (value < 40) {
        throw new Exception("value is too small");
    }
}

// Option 2 (preferred): this is bad input, so use an unchecked exception with the right meaning
public void check(int value) {
    if (value < 40) {
        throw new IllegalArgumentException("value must be >= 40, got " + value);
    }
}

Option 1 compiles, but throws Exception is far too broad and forces every caller to handle something vague. Option 2 says what actually happened: the caller passed a bad argument.

Exercise 2: Which ones throw?

The task (paraphrased): six tiny main methods (division by zero, a bad index, a bad cast, a method call on null…). Predict which throw at runtime and explain why.

Solution to Exercise 2
Snippet Result Why
Print 1 / 0 ArithmeticException: / by zero Integer division by zero
5-element array, read list[5] ArrayIndexOutOfBoundsException Valid indexes are 0..4
"abc".charAt(3) StringIndexOutOfBoundsException Valid indexes are 0..2
(String) new Object() ClassCastException The object isn’t really a String; the compiler allows it because it’s a legal downcast
Object o = null; o.toString() NullPointerException Calling a method on null
Print 1.0 / 0 No exception, prints Infinity IEEE 754 floating point: division by zero gives Infinity/NaN

The first five are all unchecked (RuntimeException), so the compiler doesn’t make you declare them and they only show up at runtime.

Exercise 3: The finally questions

The task: given try { s1; s2; s3; } catch (Ex1 e) { s4; } finally { s5; } s6; where s2 may throw, which statements run in each case?

Solution to Exercise 3
  • No exception: s1, s2, s3, s5, s6.
  • It throws Ex1: s1, s2 (throws), s4, s5, s6.
  • It throws something else: s1, s2 (throws), s5, then the exception goes to the caller; s6 does not run.

Exercise 4: Checking a score with throw and finally

The task (paraphrased): write checkScore(int score) that throws an IllegalArgumentException when the score is outside 0–10 and prints it otherwise. main reads an integer from the keyboard, calls checkScore inside a try, prints the error if there is one, and always prints a closing line in finally.

Solution to Exercise 4
import java.util.InputMismatchException;
import java.util.Scanner;

public class ScoreCheck {
    static void checkScore(int score) {
        if (score < 0 || score > 10) {
            throw new IllegalArgumentException("Invalid score: must be between 0 and 10, got " + score);
        }
        System.out.println("Your score is: " + score);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        try {
            System.out.print("Enter a score: ");
            checkScore(in.nextInt());
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        } catch (InputMismatchException e) {
            System.out.println("Error: please enter a whole number");
        } finally {
            System.out.println("Program finished.");
        }
    }
}

Running it with 8, 11 and abc:

Enter a score: 8
Your score is: 8
Program finished.

Enter a score: 11
Error: Invalid score: must be between 0 and 10, got 11
Program finished.

Enter a score: abc
Error: please enter a whole number
Program finished.
  • IllegalArgumentException is unchecked, so checkScore doesn’t need throws. Put the bad value in the message (got 11) so the log tells you immediately what happened.
  • Users can also type letters: Scanner.nextInt() throws InputMismatchException (also unchecked). If you don’t catch it, the finally line is still printed and then the program dies with a stack trace.
  • The senior move: separate validation from printing. checkScore should only check and then return or throw; what to print is the caller’s job. That makes the boundaries 0, 10, -1 and 11 trivial to unit test.

Remember

  • Explain how checked differs from unchecked, and why Error is unchecked but not a logic bug.
  • Predict which statements run when an exception passes through try-catch-finally and through several levels of the call stack.
  • Know why try-with-resources beats closing by hand in finally (suppressed exceptions), and why you never return from finally.
  • List the rules for using exceptions: keep the cause, don’t swallow, don’t throw a bare Exception, don’t use them for control flow.
  • Know where the cost of an exception lies and why a production NPE can lose its stack trace.

Interview questions

Junior

What’s the difference between checked and unchecked exceptions?

Checked exceptions are subject to the compiler’s “catch or declare” rule; unchecked ones aren’t.

Checked means subclasses of Exception outside RuntimeException; unchecked means RuntimeException and Error. Checked is meant for recoverable external failures (I/O); unchecked for programming errors and contract violations.

How is throw different from throws?

throw is a statement that throws an instance; throws is part of a method signature that declares the checked exceptions it may throw.

throws tells callers what they need to handle.

Does finally always run?

Almost always, even when the try returns or throws.

The exceptions: System.exit(), a JVM crash or kill, a thread stuck forever, or a daemon thread at JVM shutdown.

Why must a subclass catch come before its superclass?

Because catch blocks are checked top to bottom and only the first match runs.

If the superclass came first, the subclass handler could never be reached, and the compiler reports it as unreachable.

Mid

What problem does try-with-resources solve, and what is a suppressed exception?

It closes AutoCloseable resources automatically in reverse order, and it doesn’t let a close() failure overwrite the original exception.

If both the body and close() throw, the body’s exception is primary and the close() failure is attached via getSuppressed(). With a hand-written finally, the original often gets overwritten.

Senior

Are exceptions expensive? How would you optimize?

Yes: the main cost is capturing the stack trace at construction (fillInStackTrace), proportional to stack depth.

  • Don’t use exceptions for frequent control flow.
  • For high-volume business exceptions, disable the stack trace with the writableStackTrace=false constructor.
  • Be aware that OmitStackTraceInFastThrow makes repeated NPEs lose their stack traces in logs.
Where does an exception thrown in an @Async method or an executor thread go?

Not to the caller or to @ControllerAdvice; you have to handle it deliberately or it’s lost.

  • Future/CompletableFuture: it’s wrapped and surfaces on get()/join() (as ExecutionException/CompletionException).
  • A void @Async method: it goes to the AsyncUncaughtExceptionHandler (which just logs by default).
  • A plain thread: the UncaughtExceptionHandler.

Useful phrases for interviews

  • “The compiler enforces a catch-or-declare rule for checked exceptions; unchecked ones are left to the developer.”
  • “When I wrap an exception, I always pass the original as the cause so we don’t lose the stack trace.”
  • “If we see a bare NullPointerException with no stack trace in production, I’d suspect OmitStackTraceInFastThrow.”
  • “Catch blocks are checked from top to bottom, so the more specific exception has to come first.”
  • “try-with-resources closes resources in reverse order and keeps a failure in close() as a suppressed exception.”
  • “I’d never put a return in a finally block, because it silently discards the exception from the try.”
  • “Exceptions are for when a method can’t keep its contract, not for normal control flow.”
  • “Checked versus unchecked only exists in the compiler; at the bytecode level the JVM treats them the same.”

Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.