Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Exceptions

By the end of this chapter, you'll be able to

  • Catch an exception with try and catch
  • Throw an exception with throw to signal an error
  • Choose a suitable exception: IllegalArgumentException or IllegalStateException
  • Use finally and avoid swallowing an error

What happens when an exception is thrown

When an error occurs, Java creates an exception object that describes it, and interrupts the current code. The exception travels up from method to method until it finds a catch that handles it. If nobody handles it, the program stops and displays the type of the exception, its message and where it happened.

main's catch catches the exception and displays a clear message. The program carries on.

Step 5 of 5
Text description of the animation
  1. main calls pay inside a try block.
  2. pay calls debit, which does the real work.
  3. The balance isn't enough: debit throws an exception. Its execution stops dead.
  4. pay doesn't catch the exception: it stops too, and the exception travels up.
  5. main's catch catches the exception and displays a clear message. The program carries on.

try, catch, finally

int divide(int a, int b) {
    return a / b;
}

void main() {
    try {
        IO.println(divide(10, 2));
        IO.println(divide(10, 0));
        IO.println("This line is never reached");
    } catch (ArithmeticException e) {
        IO.println("Error: " + e.getMessage());
    } finally {
        IO.println("Calculations done");
    }
    IO.println("The program carries on");
}
5
Error: / by zero
Calculations done
The program carries on
  • The try block contains the code that may fail. As soon as an exception is thrown, the rest of the block is skipped.
  • catch (ExceptionType e) handles exceptions of that type. e.getMessage() gives their description. You can chain several catch blocks for different types.
  • finally runs in every case, error or not. It's used to release a resource (closing a file, a connection).

Throwing your own exceptions

A method that receives invalid data mustn't "pretend": it throws an exception with throw. Two exceptions from the standard library cover most cases:

  • IllegalArgumentException: an argument is invalid (a negative amount, a grade of 25 out of 20);
  • IllegalStateException: the state of the object doesn't allow the operation (paying with an insufficient balance, using a closed account).
class Wallet {
    private int balance;

    Wallet(int balance) {
        if (balance < 0) {
            throw new IllegalArgumentException("Negative initial balance: " + balance);
        }
        this.balance = balance;
    }

    void debit(int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Invalid amount: " + amount);
        }
        if (amount > balance) {
            throw new IllegalStateException("insufficient balance (" + balance + ")");
        }
        balance -= amount;
    }

    int getBalance() {
        return balance;
    }
}

void main() {
    var w = new Wallet(100);
    for (int amount : new int[] {30, 120, -5, 50}) {
        try {
            w.debit(amount);
            IO.println("Debit of " + amount + " accepted, " + w.getBalance() + " left");
        } catch (IllegalStateException e) {
            IO.println("Payment refused: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            IO.println("Input error: " + e.getMessage());
        }
    }
}
Debit of 30 accepted, 70 left
Payment refused: insufficient balance (70)
Input error: Invalid amount: -5
Debit of 50 accepted, 20 left

Throwing an exception rather than returning a special code (like -1 or false) has a big advantage: the error can't be ignored by accident. If the caller doesn't handle it, the program stops with a clear message, instead of carrying on with wrong data.

These exceptions are called unchecked: the compiler doesn't force you to catch them. Others, like IOException for files, are checked: a method that may throw them must declare it (throws IOException), and the caller must handle them. You'll meet them when working with files.

The catch displays the message. The balance hasn't changed: the operation was refused cleanly.

Step 4 of 4
Text description of the animation
  1. The wallet holds 70 and we try to debit 120.
  2. debit detects the problem and throws an IllegalStateException.
  3. Line 3 is skipped. Java looks for a catch of the right type: this one fits, and e refers to the exception.
  4. The catch displays the message. The balance hasn't changed: the operation was refused cleanly.

Your turn

Worked exercise

Worked exercise: the valid grade

Write a method double readGrade(String input) that converts the text into a number (accepting a comma) and throws an IllegalArgumentException if the grade isn't between 0 and 20. In main, process the list "15,5", "22", "abc" and "8": display the valid grades and a clear message for the others, then the average of the valid grades.

Hint 1
Double.parseDouble already throws a NumberFormatException for "abc". Now, NumberFormatException is a kind of IllegalArgumentException: a single catch (IllegalArgumentException e) catches both cases.
Hint 2
Count and add up the valid grades in the try, after the call to readGrade: that line is only reached if no exception was thrown.
Show the solution and common mistakes
double readGrade(String input) {
    double grade = Double.parseDouble(input.strip().replace(',', '.'));
    if (grade < 0 || grade > 20) {
        throw new IllegalArgumentException("grade outside 0 to 20: " + grade);
    }
    return grade;
}

void main() {
    double sum = 0;
    int valid = 0;
    for (String s : List.of("15,5", "22", "abc", "8")) {
        try {
            double grade = readGrade(s);
            sum += grade;
            valid++;
            IO.println("Grade accepted: " + grade);
        } catch (IllegalArgumentException e) {
            IO.println("Refused (" + s + "): " + e.getMessage());
        }
    }
    IO.println("Average: " + (valid == 0 ? 0 : sum / valid));
}
Grade accepted: 15.5
Refused (22): grade outside 0 to 20: 22.0
Refused (abc): For input string: "abc"
Grade accepted: 8.0
Average: 11.75

Common mistakes:

  • Returning -1 for an invalid grade: the caller may add it to the average without noticing.
  • Adding the grade before calling readGrade: an invalid grade would be counted before being refused.

Summary

  1. 1An exception interrupts the code and travels up to the first catch of the right type.
  2. 2try holds the risky code, catch handles the error, finally always runs.
  3. 3throw new IllegalArgumentException(…) signals an invalid argument; IllegalStateException, an incompatible state.
  4. 4An exception can't be ignored by accident, unlike a return code.
  5. 5Never leave a catch empty, and catch the most precise type possible.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.