Exceptions

Junior Always asked 7 min

On this page

The question

What is the difference between checked and unchecked exceptions?

30-second answer

A checked exception is any Exception outside RuntimeException, like IOException: the compiler makes every method that can throw it either catch it or declare it with throws. Unchecked exceptions, RuntimeException and Error with their subclasses, need neither. Use checked ones for failures a caller can expect and recover from, and unchecked ones for bugs such as a null argument.

Understand it

The Throwable hierarchy, checked and unchecked

Tap the parts

Select a part to see what it does.

Tap a part to see where it sits and whether the compiler checks it.

View as text

A class tree with Throwable at the top, split into two shaded columns: checked on the left, where the compiler says catch or declare, and unchecked on the right, with no compile check.

Throwable has two arrows: to Exception in the checked column and to Error in the unchecked column. Error shows OutOfMemoryError as an example.

Checked exceptions: Exception has arrows to IOException and to OrderException, all three in the checked column.

RuntimeException: one arrow from Exception crosses into the unchecked column to RuntimeException, which has an arrow to PaymentException.

Your exceptions: OrderException and PaymentException are marked yours. A custom exception is checked or unchecked depending on the class it extends.

A class tree with Throwable at the top, split into two shaded columns: checked on the left, where the compiler says catch or declare, and unchecked on the right, with no compile check.

Throwable has two arrows: to Exception in the checked column and to Error in the unchecked column. Error shows OutOfMemoryError as an example.

Checked exceptions: Exception has arrows to IOException and to OrderException, all three in the checked column.

RuntimeException: one arrow from Exception crosses into the unchecked column to RuntimeException, which has an arrow to PaymentException.

Your exceptions: OrderException and PaymentException are marked yours. A custom exception is checked or unchecked depending on the class it extends.

Takeaway: Error, RuntimeException and their subclasses are unchecked. Every other exception is checked: the compiler makes callers catch it or declare it.

An exception unwinding the call stack

Step by step

charge() throws a PaymentException. Nothing in charge() catches it, so the method ends at once and the exception moves to its caller.

Step 1 of 5
View as text

The call stack is drawn on top: charge() above placeOrder() above main(), each frame listing its blocks. An exception box travels down beside the frames, and a console below collects what the program prints.

charge() throws a PaymentException. Nothing in charge() catches it, so the method ends at once and the exception moves to its caller.

charge()'s frame is popped. placeOrder() has a try with only a finally, so the finally runs and prints, and the exception keeps going. The console shows finally in placeOrder.

placeOrder()'s frame is popped too. The catch in main() matches PaymentException, so it handles the exception and prints. The unwinding stops here. The console adds caught in main.

main()'s finally runs next. A finally runs after its try whether the try ended normally, returned or threw. The console adds finally in main, and the exception is marked handled.

The exception is handled, so main() goes on with the line after the try statement. With no matching catch, the thread would end with a stack trace. The console adds continues.

The call stack is drawn on top: charge() above placeOrder() above main(), each frame listing its blocks. An exception box travels down beside the frames, and a console below collects what the program prints.

charge() throws a PaymentException. Nothing in charge() catches it, so the method ends at once and the exception moves to its caller.

charge()'s frame is popped. placeOrder() has a try with only a finally, so the finally runs and prints, and the exception keeps going. The console shows finally in placeOrder.

placeOrder()'s frame is popped too. The catch in main() matches PaymentException, so it handles the exception and prints. The unwinding stops here. The console adds caught in main.

main()'s finally runs next. A finally runs after its try whether the try ended normally, returned or threw. The console adds finally in main, and the exception is marked handled.

The exception is handled, so main() goes on with the line after the try statement. With no matching catch, the thread would end with a stack trace. The console adds continues.

Takeaway: An exception leaves every method that does not catch it, running that method's finally on the way out, until a matching catch handles it.

The Throwable hierarchy, checked and uncheckedThrowable has two subclasses, Error and Exception. Error is unchecked. Exception is checked, and so are its other subclasses. RuntimeException extends Exception, but it and its subclasses are unchecked.ThrowableErroruncheckedExceptioncheckedRuntimeExceptionunchecked
The Throwable hierarchy, checked and uncheckedThrowable has two subclasses, Error and Exception. Error is unchecked. Exception is checked, and so are its other subclasses. RuntimeException extends Exception, but it and its subclasses are unchecked.ThrowableErroruncheckedExceptioncheckedRuntimeExceptionunchecked
Throwable splits into Error and Exception; Error and RuntimeException are unchecked

In code

class PaymentException extends RuntimeException {
    PaymentException(String message) { super(message); }
}

static void charge(Order order) {
    throw new PaymentException("card declined");
}

static void placeOrder(Order order) {
    try {
        charge(order);
    } finally {
        System.out.println("finally in placeOrder");   // 1st
    }
}

public static void main(String[] args) {
    try {
        placeOrder(new Order());
    } catch (PaymentException e) {
        System.out.println("caught in main");          // 2nd
    } finally {
        System.out.println("finally in main");         // 3rd
    }
    System.out.println("continues");                   // 4th
}
An exception runs each finally on its way to a catch
record Res(String name) implements AutoCloseable {
    Res { System.out.println("open " + name); }
    public void close() { System.out.println("close " + name); }
}

try (Res a = new Res("A"); Res b = new Res("B")) {
    throw new IllegalStateException("body");
} catch (IllegalStateException e) {
    System.out.println("catch " + e.getMessage());
}
// open A, open B, close B, close A, catch body
try-with-resources closes in reverse order, then catch runs
try-with-resources with two resourcesThe try statement opens resource A, then resource B. The body throws. Java closes B first, then A, in the reverse order of opening, and only then runs the catch block.resource Bresource Atrybody throwscatch runsopenopenclose()close()
try-with-resources with two resourcesThe try statement opens resource A, then resource B. The body throws. Java closes B first, then A, in the reverse order of opening, and only then runs the catch block.resource Bresource Atrybody throwscatch runsopenopenclose()close()
try-with-resources closes B, then A, before catch runs
class OrderNotSavedException extends RuntimeException {
    OrderNotSavedException(long id, Throwable cause) { super("order " + id + " not saved", cause); }
}

try {
    repository.save(order);
} catch (SQLException e) {
    throw new OrderNotSavedException(order.id(), e);   // the stack trace shows both, "Caused by: ..."
}
Wrap a low-level exception and keep it as the cause

Solve it

Where did the exception go?

parsePort("abc") should fail, but it returns -1 and nothing is logged. The method parses in a try and has return -1; in its finally “as a safe default”. Explain what happens and fix it.

  1. Trace the throw. Integer.parseInt("abc") throws NumberFormatException. Before it leaves the method, finally runs.
  2. Trace the finally. return -1 completes the method normally. A return or throw in finally replaces the pending exception, which is discarded.
  3. State the rule. finally is for cleanup. Never return or throw from it.
  4. Fix it. Catch the specific exception and decide on purpose: rethrow with context, or return a default and log it. Move cleanup to try-with-resources.
  5. Check. A test expects IllegalArgumentException for "abc" and 8080 for "8080".
static int parsePortBroken(String s) {
    try {
        return Integer.parseInt(s);
 Wrong     } finally { return -1; }                 // always -1, and the exception is lost
}

static int parsePort(String s) {
    try {
        return Integer.parseInt(s);
 Right     } catch (NumberFormatException e) {
        throw new IllegalArgumentException("port must be a number: " + s, e);
    }
}
A return in finally swallows the exception

How to answer

  • Checked: Exception and its subclasses outside RuntimeException; the compiler enforces catch or declare.
  • Unchecked: RuntimeException, Error and their subclasses; no catch or throws is needed.
  • The check happens only at compile time; at runtime both kinds unwind the stack the same way.
  • Checked exceptions suit recoverable failures, such as a missing file; unchecked ones suit bugs and broken preconditions.
  • A lambda passed to Function or Consumer cannot throw a checked exception, one reason many APIs prefer unchecked ones.

Common mistakes

  • Saying unchecked exceptions cannot be caught; any Throwable can be caught, the compiler just does not force it.
  • Putting RuntimeException on the checked side because it extends Exception.

Follow-up questions

What is the difference between Error and Exception?

Both extend Throwable. An Error signals a serious problem in the JVM (Java Virtual Machine) or its environment, such as OutOfMemoryError or StackOverflowError, that a reasonable application should not try to catch. An Exception signals a condition the program may handle, like a missing file or invalid input. Errors are unchecked; exceptions are checked unless they extend RuntimeException.

  • Error: trouble in the JVM or its environment, such as OutOfMemoryError and StackOverflowError; usually not caught.
  • Exception: conditions an application can anticipate and handle.
  • catch (Exception e) does not catch an Error.
Throwable oom = new OutOfMemoryError();
System.out.println(oom instanceof Error);      // true
System.out.println(oom instanceof Exception);  // false: catch (Exception e) misses it

See it in the infographic: The Throwable hierarchy, checked and unchecked

How does try-with-resources work?

You declare resources in parentheses after try, and each must implement AutoCloseable. When the block ends, normally or with an exception, Java closes them in the reverse order of opening, before any catch or finally runs. If close() also throws, that exception is added to the body's exception as a suppressed one instead of replacing it.

  • Resources must implement AutoCloseable; Closeable extends it.
  • They close in reverse order, before catch and finally run.
  • A close() failure is attached with addSuppressed(); read it with getSuppressed().
  • Since Java 9, an effectively final variable can be listed directly: try (in) { ... }.
record Res(String name) implements AutoCloseable {
    Res { System.out.println("open " + name); }
    public void close() { System.out.println("close " + name); }
}

try (Res a = new Res("A"); Res b = new Res("B")) {
    throw new IllegalStateException("body");
} catch (IllegalStateException e) {
    System.out.println("catch " + e.getMessage());
}
// open A, open B, close B, close A, catch body

See it in the infographic: An exception unwinding the call stack

How do you write a custom exception, and should it be checked or unchecked?

Extend Exception for a checked exception or RuntimeException for an unchecked one, name it after the problem, and pass a message and, when you wrap another failure, its cause to super. Make it checked when callers can reasonably recover, like OrderException for an order that cannot be saved, and unchecked when most callers cannot do anything about it.

  • Extend Exception for checked or RuntimeException for unchecked, not Throwable or Error.
  • Offer constructors that take a message and a cause, and pass both to super.
  • Add fields for context, such as the order id, rather than parsing the message.
class OrderException extends Exception {          // checked
    OrderException(String message, Throwable cause) {
        super(message, cause);
    }
}

class PaymentException extends RuntimeException { // unchecked
    PaymentException(String message) { super(message); }
}

See it in the infographic: The Throwable hierarchy, checked and unchecked

Does finally run if the try block returns? What if finally returns too?

Yes. The return value is computed first, then finally runs, then the method returns, so changing a local in finally does not change an int already being returned. A return in finally wins: try { return 1; } finally { return 2; } returns 2, and it even discards an exception thrown in the try. finally is skipped only if the JVM stops, for example with System.exit().

  • finally runs after a normal end, a return or an exception.
  • The returned value is evaluated before finally runs.
  • A return or throw in finally replaces the outcome of the try; javac -Xlint warns about it.
static int value() {
    int x = 1;
    try { return x; }      // 1 is evaluated here
    finally { x = 2; }     // too late to change the result
}

static int override() {
    try { return 1; }
    finally { return 2; }  // wins: the method returns 2
}

See it in the infographic: An exception unwinding the call stack

What is exception translation, and why keep the cause?

Exception translation means catching a low-level exception and throwing one that fits your layer, with the original as its cause. A repository catches SQLException and throws OrderException. Callers depend on your abstraction instead of JDBC (Java Database Connectivity), and the cause keeps the original failure and its stack trace, printed under "Caused by:".

  • Always pass the original exception as the cause; never drop it.
  • Translate at layer boundaries, so callers see exceptions from their own domain.
  • getCause() returns the wrapped exception.
void saveOrder(Order order) throws OrderException {
    try {
        repository.save(order);
    } catch (SQLException e) {
        throw new OrderException("could not save order " + order.id(), e);
    }
}

See it in the infographic: The Throwable hierarchy, checked and unchecked

Should you catch Exception or Throwable?

Rarely. catch (Exception e) also catches every RuntimeException, so a bug such as a NullPointerException is swallowed along with the failure you expected, and catch (Throwable t) also catches Errors such as OutOfMemoryError. Catch the specific types you can handle. A broad catch belongs only at a boundary, such as a request handler or a thread's top level, to log and fail cleanly.

What are suppressed exceptions?

When a try-with-resources body throws and closing a resource throws too, the body's exception is the one that propagates, and the close() exception is attached to it with addSuppressed(). getSuppressed() returns them. A plain finally that throws does the opposite: its exception replaces the original one, which is lost.

Why does Spring prefer unchecked exceptions?

Most data access failures cannot be fixed by the method that sees them, so forcing every layer to catch or declare them only adds noise. Spring translates checked exceptions such as SQLException into its unchecked DataAccessException hierarchy, and @Transactional rolls back by default on RuntimeException and Error, not on checked exceptions.

Check yourself

1. charge() throws a PaymentException, which extends RuntimeException. What does main print?
static void placeOrder() {
    try { charge(); }
    finally { System.out.print("A "); }
}
public static void main(String[] args) {
    try { placeOrder(); }
    catch (PaymentException e) { System.out.print("B "); }
    finally { System.out.print("C "); }
    System.out.print("D");
}
Show answers
  • A B C D: Correct. placeOrder's finally runs as the exception leaves it, then main's catch, main's finally and the next line.
  • B A C D: Incorrect. The exception must leave placeOrder before main's catch sees it, so A comes first.
  • B C D: Incorrect. A finally runs even when its try has no catch, so A is printed.
  • A B C: Incorrect. The catch handles the exception, so main goes on and prints D.
2. Which of these exceptions are checked?Choose 2
Show answers
  • IOException: Correct. It extends Exception and not RuntimeException, so it is checked.
  • IllegalArgumentException: Incorrect. It extends RuntimeException, so it is unchecked.
  • OrderException extends Exception: Correct. A custom exception that extends Exception is checked.
  • StackOverflowError: Incorrect. Every Error is unchecked.
  • PaymentException extends RuntimeException: Incorrect. A custom exception that extends RuntimeException is unchecked.
3. What happens when this method is compiled?
void loadOrders(Path file) {
    throw new IOException("cannot read " + file);
}
Show answers
  • It compiles and throws at runtime: Incorrect. IOException is checked, so the compiler rejects it before anything runs.
  • Compile error: unreported exception IOException: Correct. A checked exception must be caught or declared with throws IOException.
  • It compiles, because IOException is unchecked: Incorrect. IOException extends Exception, not RuntimeException, so it is checked.