Codiqo

Learn Java · lesson 44 of 61 · about 8 minutes

Exceptions

Check the snack vouchers: throw and catch exceptions, use finally, and create your own exception type.

What you'll learn

  • Throw an exception
  • Catch it with try/catch
  • Define a custom exception

The snack vouchers

Customers hand over snack vouchers: POP is worth $4.50 and SODA $3.00. redeem(code) returns a voucher's value, but some codes can't give a sensible number: a code ending in -OLD has run out, so it throws the desk's own ExpiredVoucherException, and an unknown code throws an IllegalArgumentException. The voucher loop calls redeem inside try, catches the expired ones first and everything else after, and counts every voucher in finally, whatever happened.

Throw, catch and finally

public class Main {
    static void setLives(int n) {
        if (n < 0) throw new IllegalArgumentException("lives can't be negative");
    }

    public static void main(String[] args) {
        try {
            setLives(-1);
            System.out.println("ok");
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        } finally {
            System.out.println("checked");
        }
    }
}

Output

lives can't be negative
checked

When something goes wrong

throw new IllegalArgumentException("...") stops the method and jumps to the nearest matching catch. finally always runs, error or not.

Common built-in types: IllegalArgumentException (bad input), IllegalStateException (wrong time to do this), NumberFormatException (bad number text). You can define your own by extending RuntimeException.

Throwing and catching

class InsufficientFundsException extends RuntimeException {
    InsufficientFundsException(String message) {
        super(message);
    }
}

public class Main {
    static int withdraw(int balance, int amount) {
        if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
        if (amount > balance) throw new InsufficientFundsException("need " + (amount - balance) + " more");
        return balance - amount;
    }

    public static void main(String[] args) {
        try {
            System.out.println(withdraw(50, 20));
            System.out.println(withdraw(50, 80));
        } catch (InsufficientFundsException e) {
            System.out.println("Sorry: " + e.getMessage());
        } finally {
            System.out.println("Done");
        }
        try {
            Integer.parseInt("12a");
        } catch (NumberFormatException e) {
            System.out.println("Not a number");
        }
    }
}

Output

30
Sorry: need 30 more
Done
Not a number

A more specific exception, caught first

Your own exception can extend a built-in one, so it's a more specific kind of that problem. Catches are tried from top to bottom, and a catch also matches every type that extends its own, so the specific one has to come first. The other way round, javac refuses: the general catch would already have caught everything.

Sold out, or just not enough seats

class SoldOutException extends IllegalStateException {
    SoldOutException(String message) {
        super(message);
    }
}

public class Main {
    static void book(int seatsLeft, int wanted) {
        if (seatsLeft == 0) throw new SoldOutException("the showing is sold out");
        if (wanted > seatsLeft) throw new IllegalStateException("only " + seatsLeft + " seats left");
        System.out.println("Booked " + wanted);
    }

    public static void main(String[] args) {
        int[][] tries = {{5, 2}, {0, 1}, {3, 4}};
        for (int[] t : tries) {
            try {
                book(t[0], t[1]);
            } catch (SoldOutException e) {
                System.out.println("Sold out: " + e.getMessage());
            } catch (IllegalStateException e) {
                System.out.println("Can't book: " + e.getMessage());
            }
        }
    }
}

Output

Booked 2
Sold out: the showing is sold out
Can't book: only 3 seats left

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.