×

java · level 2 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

an exception when a value makes no sense.

Your setters quietly ignored bad values, so nobody ever found out. Louder is often better. throw new IllegalArgumentException("Age cannot be negative"); stops the method at once and hands the problem to whoever called it. They can catch it, or the program stops.

IllegalArgumentException belongs to the family, the unchecked exceptions. Java does not force anyone to catch them, because they usually mean a mistake in the calling code, which should be fixed rather than handled.

public class Main {
    static int ticketPrice(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative: " + age);
        }
        if (age < 16) {
            return 5;
        }
        return 10;
    }
    public static void main(String[] args) {
        try {
            System.out.println(ticketPrice(12));
            System.out.println(ticketPrice(-3));
            System.out.println(ticketPrice(40));
        } catch (IllegalArgumentException e) {
            System.out.println("Problem: " + e.getMessage());
        }
    }
}

The message you give the exception is what getMessage() hands back later.