IntermediateLesson 12 of 205 min read

Exceptions: try, catch, finally and Custom Errors

Learn how Java reports errors with exceptions, how to catch and rethrow them, how try-with-resources cleans up, and how to design your own exception, with real stack output.

In this lesson you will

  • Throw and catch exceptions
  • Use finally and try-with-resources
  • Tell checked from unchecked
  • Write a custom exception

About 28 minutes

When the booking file is missing

Hana’s program reads bookings from a file, and one morning the file is not there. Without a plan the program stops with a wall of red text. An exception is an object that Java creates when something goes wrong, and it travels up through the callers until some code catches it or the program ends. Handling exceptions well means deciding, for each failure, who can do something useful about it.

Code that might fail goes in a try block, and a catch block handles a particular kind of exception. A finally block runs whatever happens, which is where you release resources. Resources that implement AutoCloseable can be declared in the parentheses of a try, which closes them automatically, in the reverse order of opening, even when an exception is thrown. Exceptions come in two families. Checked exceptions, such as IOException, must be caught or declared with throws, so the compiler forces you to think about them. Unchecked exceptions, which extend RuntimeException, such as NullPointerException and IllegalArgumentException, usually signal a programming error and need no declaration.

Kind Examples Must you handle it?
Checked IOException, SQLException Yes: catch or declare
Unchecked IllegalArgumentException, NullPointerException No, but fix the cause
Error OutOfMemoryError No: the JVM is in trouble
import java.util.*;

class BookingException extends Exception {
    private final String bike;
    BookingException(String message, String bike, Throwable cause) { super(message, cause); this.bike = bike; }
    String bike() { return bike; }
}
class Tracer implements AutoCloseable {
    private final String name;
    static final List<String> log = new ArrayList<>();
    Tracer(String name) { this.name = name; log.add("open " + name); }
    @Override public void close() { log.add("close " + name); }
}
public class Main {
    static int parseDays(String s) { return Integer.parseInt(s); }
    static int book(String bike, String days) throws BookingException {
        try {
            int d = parseDays(days);
            if (d < 1) throw new IllegalArgumentException("days must be positive: " + d);
            return d * 1200;
        } catch (NumberFormatException e) {
            throw new BookingException("days is not a number", bike, e);
        }
    }
    public static void main(String[] args) {
        String[][] tests = {{"City 1", "3"}, {"Trail 2", "x3"}, {"Tandem 3", "0"}};
        for (String[] t : tests) {
            try {
                System.out.println(t[0] + " -> " + book(t[0], t[1]));
            } catch (BookingException e) {
                System.out.println("BookingException for " + e.bike() + ": " + e.getMessage() + " (cause: " + e.getCause().getClass().getSimpleName() + ")");
            } catch (RuntimeException e) {
                System.out.println("RuntimeException: " + e.getMessage());
            } finally {
                System.out.println("  finished " + t[0]);
            }
        }
        try (Tracer a = new Tracer("A"); Tracer b = new Tracer("B")) {
            Tracer.log.add("body");
            throw new IllegalStateException("boom");
        } catch (IllegalStateException e) {
            Tracer.log.add("caught " + e.getMessage());
        }
        System.out.println(Tracer.log);
        int[] arr = new int[2];
        try { arr[5] = 1; } catch (ArrayIndexOutOfBoundsException | NullPointerException e) { System.out.println("multi-catch: " + e.getClass().getSimpleName()); }
    }
}
City 1 -> 3600
  finished City 1
BookingException for Trail 2: days is not a number (cause: NumberFormatException)
  finished Trail 2
RuntimeException: days must be positive: 0
  finished Tandem 3
[open A, open B, body, close B, close A, caught boom]
multi-catch: ArrayIndexOutOfBoundsException

The first booking worked and cost 3600. The second failed in Integer.parseInt with a NumberFormatException, which the book method caught and wrapped in our own BookingException, keeping the original as the cause, so the report says both what we were doing and what went wrong. The third was a negative-or-zero value, which is an unchecked IllegalArgumentException that the second catch block handled. Because the catch blocks are tried from the top, the specific BookingException must come before the general RuntimeException. The finally block ran 3 times, once for each test, whether or not an exception happened.

The try-with-resources part shows the order. The log reads [open A, open B, body, close B, close A, caught boom]: the resources were opened as A and then B, the body ran and threw, then B and A were closed in reverse order before the catch block ran. This is why try-with-resources is safer than closing by hand in finally: you cannot forget to close, and a failure in the body does not leak the resource. The last line used a multi-catch, which handles two unrelated exception types in one block.

Check by hand: 3 x 1200 = 3600. Integer.parseInt(“x3”) cannot read an x, so a NumberFormatException is certain. For the log, resources close in the reverse of opening order, B before A, and the catch runs after the resources are closed, so “caught boom” is last.

Never swallow an exception silently

An empty catch block hides problems. At least log the error, and if you cannot handle it, let it propagate to someone who can.

Throw early, catch late

Check inputs and throw at the point where the problem is detected. Catch where you know what to do about it, often at the edge of the program.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21.

Practice

Write a method that reads a number from a string and returns -1 for bad input, and then rewrite it to throw a custom exception instead. Decide which design is better when the caller must tell a bad value from a legitimate -1.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Where does code that releases resources belong?

  1. In finally or try-with-resources
  2. In the constructor
  3. In main only
  4. Nowhere

So that it always runs.

Which exceptions must be caught or declared?

  1. Unchecked exceptions
  2. Errors
  3. None
  4. Checked exceptions

IOException is an example.

In which order do try-with-resources close?

  1. Opening order
  2. Random
  3. Alphabetical
  4. Reverse of opening

B closed before A.

Why wrap an exception in a custom one?

  1. To hide it
  2. To make it unchecked
  3. To add context and keep the cause
  4. To speed up the program

getCause returns the original.

What order should catch blocks follow?

  1. General before specific
  2. Alphabetical
  3. Specific before general
  4. Any order

A general block first would hide the specific one.

Summary

  • Exceptions travel up the call stack until caught.
  • finally and try-with-resources clean up, closing in reverse order.
  • Checked exceptions are enforced by the compiler; unchecked ones usually mean a bug.
  • Wrap with context and keep the cause.

Next lesson

Lesson 13 covers files: reading and writing text with java.nio.

Questions

What does throws do?

It declares in a method header that the method may throw a checked exception, so callers must handle it.

What is a stack trace?

A list of the method calls that led to the exception. Read it from the top to find where it was thrown.

Should I catch Exception?

Rarely. Catching the general type can hide bugs. Catch the specific types you can handle.

Progress is saved in this browser.