×

java · level 2 · unit 6 · lesson 4

  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

Make your own exception, and Java makes callers face it.

Some problems are nobody's fault: a shop runs out of stock, or a file goes missing. Java calls these checked exceptions. They extend Exception but not RuntimeException, and Java checks that every caller deals with them before the program can run.

Make a by extending Exception, with a constructor that hands the message to super. A method that can throw it says so with after its brackets. Each caller must then catch it, or declare it in turn.

public class Main {
    static class OutOfStockException extends Exception {
        OutOfStockException(String message) { super(message); }
    }
    static void buy(String cake, int left) throws OutOfStockException {
        if (left == 0) {
            throw new OutOfStockException("Sorry, no " + cake + " left");
        }
        System.out.println("One " + cake + ", coming up!");
    }
    public static void main(String[] args) {
        try {
            buy("cupcake", 3);
            buy("eclair", 0);
        } catch (OutOfStockException e) {
            System.out.println(e.getMessage());
        }
    }
}

Name an exception after its problem, and end the name with Exception.