×

java · level 2 · unit 6 · lesson 2

  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

Many problems, many catches, and a that always runs.

One try can have several catch blocks, one for each kind of problem. Java checks them from the top and runs only the first that matches. Dividing a whole number by zero, for example, gives an .

A finally block goes at the very end, and it always runs: after a clean try, after a catch, even while an uncaught exception is on its way out. It is the place to tidy up, like switching off the lights as you leave.

public class Main {
    static void share(String sweets, int friends) {
        try {
            int each = Integer.parseInt(sweets) / friends;
            System.out.println("Each friend gets " + each);
        } catch (NumberFormatException e) {
            System.out.println("That is not a number of sweets");
        } catch (ArithmeticException e) {
            System.out.println("Nobody to share with");
        } finally {
            System.out.println("Bag closed");
        }
    }
    public static void main(String[] args) {
        share("12", 4);
        share("lots", 4);
        share("12", 0);
    }
}

finally is the right home for goodbyes, saving work and closing things you opened.