IAE Academy

FOR CORE AND IT JOBS · CHAPTER 5 OF 7

Exceptions

An exception is an object thrown when a method cannot continue, and it travels up the call stack until some code catches it. This chapter explains that travel, how try, catch, finally and try-with-resources control it, and how to throw your own exceptions, so your programs fail clearly and close the files they open.

Updated 30 Oct 2026

What you will be able to do

You will say exactly which lines of a Java program run when an exception is thrown deep inside nested calls. You will choose between checked and unchecked exceptions, write try, catch, finally and try-with-resources correctly, and write a custom exception. You will also decide whether to catch an exception or let it propagate.

Before you start

  1. Chapter 4, Polymorphism, abstract classes and interfaces (a subclass object can stand in for its superclass)

  2. A class that extends another, and a constructor that calls super(...)

  3. static methods and fields, fields declared final, and joining strings with +

  4. Arrays and their indexes, and calling one method from another

What an exception is and where it goes

A method sometimes cannot do its job: an array index is out of range, a file is missing, an integer is divided by zero. Java then creates an exception object and throws it, and the method stops at that line. If the method does not handle the exception (the next section shows how), it goes to the caller, then to its caller, and so on. Every running call has a frame on the call stack, and each frame is removed as the exception passes. This is called unwinding.

Here main calls a, a calls b, b calls c, and c fails. All code in this chapter is Java 17.

public class Demo {
    static void c() { int[] v = new int[2]; v[5] = 1; }
    static void b() { c(); }
    static void a() { b(); }
    public static void main(String[] args) { a(); }
}
// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
//   Index 5 out of bounds for length 2
// then one "at" line each for c, b, a and main

Nothing handles it, so every frame is removed and the program ends with a stack trace.

UNWINDING THE CALL STACK

Holds when no method on the way handles the exception, as in Demo. Popping a frame abandons the rest of that method's lines. The next section shows how a matching catch stops the unwinding at its frame. If nothing handles it, main's frame goes too, and the program stops and prints the stack trace.

Every thrown object belongs to a class tree. The top class is Throwable. Under it sit Error, for serious failures such as running out of memory that a program should not try to handle, and Exception, for problems a program can reasonably handle. The compiler also sorts these classes into checked and unchecked. A method that can let a checked exception escape must say so with throws and the class name in its header, as in void load() throws IOException.

THE THROWABLE HIERARCHY IN OUTLINE

The symbol means A is a superclass of B. Only objects of Throwable or its subclasses can be thrown or caught. RuntimeException extends Exception, yet it is unchecked, as the table shows.

Kind

Which classes

Must you catch or declare it?

Typical examples

Checked

Exception and its subclasses, except RuntimeException and its subclasses; also Throwable itself

Yes. The compiler refuses the code otherwise

IOException, a custom class that extends Exception

Unchecked

RuntimeException and its subclasses, and Error and its subclasses

No

NullPointerException, ArithmeticException, StackOverflowError

try, catch, finally and resources

A try block holds the code that may throw. A catch block names the type it handles. When an exception is thrown inside the try, the remaining lines of the try are skipped and Java looks at the catch blocks from top to bottom. A finally block holds clean-up that must happen whatever the outcome.

WHICH CATCH BLOCK RUNS

T is the declared catch type; a thrown object is a T if its class is T or a subclass of T. At most one catch runs. If none matches, the exception carries on outward after finally. Put a subclass catch above its superclass catch, or the compiler rejects the code as unreachable.

WHAT FINALLY ALWAYS DOES

Exits include normal completion, a caught or uncaught exception, return, break and continue. finally is skipped only if the try or catch never finishes or the program is stopped, as with System.exit. A returned value is copied before finally runs: reassigning the variable in finally has no effect, but changes to an object it refers to reach the caller. A return in finally would replace the result.

Files, sockets and database connections must be closed. Writing close in finally works but is long. Try-with-resources closes them for you: declare the resource in parentheses after try. Its class must implement AutoCloseable, as BufferedReader does. Opening and reading a file can throw IOException, a checked exception, so this method declares it with throws.

import java.io.*;

public class FirstLine {
    static String firstLine(String path) throws IOException {
        try (BufferedReader r = new BufferedReader(new FileReader(path))) {
            return r.readLine();
        }
    }
}
// returns the file's first line (null if empty); r.close() runs before the
// method returns or throws, even if readLine throws

CLOSING ORDER IN TRY-WITH-RESOURCES

Resources to are declared in the parentheses, left to right, separated by semicolons. Every resource that was opened is closed, even if the body throws. Closing happens before any catch or finally of the same statement runs.

Throwing, custom exceptions and propagation

You throw with the throw keyword and a Throwable object, usually a new one: throw new IllegalArgumentException("negative"). The method stops there unless a try around it in the same method catches the exception. Callers of a method that declares a checked exception with throws must handle it or declare it in turn. Your own exception class passes a message to super, and extra fields, such as an amount, give the handler more to work with.

CUSTOM EXCEPTION AND ITS KIND

Holds whether the class extends Exception or RuntimeException directly or through one of their subclasses. A class under RuntimeException is unchecked even though RuntimeException is itself under Exception. A checked custom exception needs throws on every method that can let it escape.

CATCH OR PROPAGATE

Catch the most specific type you can handle. Catching Exception for everything also catches bugs such as a null reference and hides them. If you cannot recover, let the exception propagate: declare throws for a checked exception; an unchecked one passes up with no declaration.

WORKED EXAMPLE

What does this program print?

class InsufficientFundsException extends Exception {
    private final int shortBy;
    InsufficientFundsException(String message, int shortBy) {
        super(message);
        this.shortBy = shortBy;
    }
    int getShortBy() { return shortBy; }
}

public class Bank {
    static int balance = 500;
    static void withdraw(int amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("need more", amount - balance);
        }
        balance -= amount;
    }
    public static void main(String[] args) {
        try {
            withdraw(200);
            withdraw(800);
            System.out.println("paid");
        } catch (InsufficientFundsException e) {
            System.out.println(e.getMessage() + " " + e.getShortBy());
        }
    }
}
Solution
  1. withdraw(200): 200 > 500 is false, so nothing is thrown and balance becomes 500 - 200 = 300.

  2. withdraw(800): 800 > 300 is true, so the exception is created with shortBy = 800 - 300 = 500 and thrown. withdraw ends at the throw, so balance stays 300.

  3. The exception reaches main's try, so the line printing paid is skipped.

  4. The object is an InsufficientFundsException, the catch type, so that catch runs. getMessage(), inherited from Throwable, returns the message given to super; getShortBy() returns 500.

Answer: need more 500

WORKED EXAMPLE

Trace this program. Which lines print, in order?

public class Trace {
    static void inner(int n) {
        System.out.println("inner start " + n);
        if (n == 0) throw new IllegalStateException("zero");
        System.out.println("inner end " + n);
    }
    static void middle(int n) {
        try {
            System.out.println("middle try");
            inner(n);
            System.out.println("middle after inner");
        } finally {
            System.out.println("middle finally");
        }
    }
    public static void main(String[] args) {
        try {
            middle(1);
            middle(0);
            System.out.println("main after middle");
        } catch (IllegalStateException e) {
            System.out.println("main caught " + e.getMessage());
        }
        System.out.println("main done");
    }
}
Solution
  1. middle(1): nothing is thrown, so every line runs: middle try, inner start 1, inner end 1, middle after inner, then middle finally as the try ends normally.

  2. middle(0): middle try, then inner start 0. Now n == 0, so inner throws. inner has no try, so its frame is popped and inner end 0 never prints.

  3. In middle, middle after inner is skipped. Its try has no catch, but its finally still runs: middle finally. Then middle's frame is popped too.

  4. In main the call was inside the try, so main after middle is skipped. IllegalStateException matches the catch type: main caught zero.

  5. The exception is now handled, so the program continues after the catch: main done.

Answer: middle try, inner start 1, inner end 1, middle after inner, middle finally, middle try, inner start 0, middle finally, main caught zero, main done

Check yourself

CHECK YOURSELF 1

Which of these is a checked exception?

  1. (A)

    NullPointerException

  2. (B)

    IOException

  3. (C)

    ArithmeticException

  4. (D)

    StackOverflowError

Answer and solution

Answer: (B)

  1. NullPointerException and ArithmeticException extend RuntimeException, so they are unchecked.

  2. StackOverflowError is an Error, so it is unchecked.

  3. IOException extends Exception and not RuntimeException, so it is checked.

CHECK YOURSELF 2

A try block calls a method that can throw FileNotFoundException, which is a subclass of IOException. The try has catch (IOException e) first and catch (FileNotFoundException e) second. What happens?

  1. (A)

    The second catch runs because it is more specific

  2. (B)

    The code does not compile because the second catch can never run

  3. (C)

    The first catch runs and the second is ignored silently

  4. (D)

    Both catch blocks run in order

Answer and solution

Answer: (B)

  1. Catch blocks are tested top to bottom and the first match runs.

  2. A FileNotFoundException is an IOException, so the first block would always take it.

  3. The compiler detects that the second block is unreachable and rejects the code.

CHECK YOURSELF 3

This method is part of a class. What integer does the call g() return?

static int g() {
    int x = 10;
    try {
        x = 20;
        return x;
    } finally {
        x = 30;
    }
}
Answer and solution

Answer:

  1. In the try, x becomes 20 and return x fixes the value 20 as the result.

  2. finally runs next and sets x to 30, but the result has already been copied.

  3. The method returns 20.

CHECK YOURSELF 4One or more options are correct

Which statements about try-with-resources are true?

  1. (A)

    Each resource's class must implement AutoCloseable

  2. (B)

    Resources are closed in the reverse order of their declaration

  3. (C)

    Resources are closed only if the body finishes without throwing

  4. (D)

    A catch clause is required on the statement

Answer and solution

Answer: (A), (B)

  1. A is true: the resource's class must implement AutoCloseable.

  2. B is true: the last resource declared is closed first.

  3. C is false: resources are closed even when the body throws.

  4. D is false: catch and finally are optional; a checked exception from opening or closing must then be handled elsewhere, for example declared with throws.