Chapter 4 · Robust, modern Java

Exceptions

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 22 · Concept

When things go wrong

In lesson 4 a division by zero stopped a program with an exception. An exception does not have to end the program.

In this lesson you will:

  • catch an exception and carry on,
  • throw one from a method that checks its input,
  • write an exception class of your own.
public class Catch {
    public static void main(String[] args) {
        try {
            System.out.println("A");
            int n = Integer.parseInt("forty");
            System.out.println("B");
        } catch (NumberFormatException e) {
            System.out.println("C");
        }
        System.out.println("D");
    }
}
public class Parse {
    public static void main(String[] args) {
        String[] inputs = {"42", "forty", "7"};
        int total = 0;
        for (String text : inputs) {
            try {
                total += Integer.parseInt(text);
                System.out.println("read " + text);
            } catch (NumberFormatException e) {
                String why = e.getMessage();
                System.out.println("skipped: " + why);
            }
        }
        System.out.println("total " + total);
    }
}
public class ParseOr {
    // write parseOr here

    public static void main(String[] args) {
        System.out.print(parseOr("12", 0) + " ");
        System.out.print(parseOr("twelve", -1) + " ");
        System.out.println(parseOr("", 0));
    }
}
public class Finally {
    static void check(String text) {
        try {
            int n = Integer.parseInt(text);
            System.out.println("number " + n);
        } catch (NumberFormatException e) {
            System.out.println("not a number");
        } finally {
            System.out.println("done with " + text);
        }
    }

    public static void main(String[] args) {
        check("5");
        check("five");
    }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Account("Ada", 50);
        try {
            a.withdraw(80);
        } catch (IllegalArgumentException e) {
            System.out.println("Refused: " + e.getMessage());
        }
        System.out.println(a);
        a.withdraw(-5);
        System.out.println("never printed");
    }
}
public class Main {
    public static void main(String[] args) {
        Account a = new Account("Grace", 10);
        int[] amounts = {5, 0, -3, 20};
        for (int amount : amounts) {
            try {
                a.deposit(amount);
            } catch (IllegalArgumentException e) {
                String why = e.getMessage();
                System.out.println("Refused: " + why);
            }
        }
        System.out.println(a);
    }
}
public class Amount {
    static int amount(String text) {
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(
                    "not an amount: " + text);
        }
    }

    public static void main(String[] args) {
        String[] inputs = {"30", "thirty"};
        for (String text : inputs) {
            try {
                System.out.println("amount " + amount(text));
            } catch (IllegalArgumentException e) {
                String why = e.getMessage();
                System.out.println("Refused: " + why);
            }
        }
    }
}
public class Tickets {
    static int book(int left, int seats) {
        if (seats > left) {
            throw new SoldOutException(
                    "only " + left + " seats left");
        }
        return left - seats;
    }

    public static void main(String[] args) {
        int left = 5;
        try {
            left = book(left, 3);
            System.out.println("booked 3, " + left + " left");
            left = book(left, 3);
            System.out.println("booked 3 more");
        } catch (SoldOutException e) {
            System.out.println("Sorry: " + e.getMessage());
        }
    }
}
public class Main {
    public static void main(String[] args) {
        Wallet w = new Wallet();
        String[] inputs = {"50", "ten", "-5", "20"};
        for (String text : inputs) {
            try {
                w.insert(text);
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        }
        System.out.println("coins: " + w.coins());
        try {
            w.pay(30);
            System.out.println("paid 30, coins: " + w.coins());
            w.pay(60);
            System.out.println("paid 60");
        } catch (NotEnoughMoneyException e) {
            System.out.println("refused: " + e.getMessage());
        } finally {
            System.out.println("coins: " + w.coins());
        }
    }
}
public class Menu {
    public static void main(String[] args) {
        int[] prices = {5, 8, 2, 7};
        String[] picks = {"3", "x", "9"};
        for (String pick : picks) {
            try {
                int i = Integer.parseInt(pick);
                System.out.println("price " + prices[i]);
            } catch (NumberFormatException e) {
                System.out.println("no such item: " + pick);
            }
        }
    }
}
Terminal
Step 1 of 10try and catch

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)