×

java · level 2 · unit 6 · lesson 1

  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

the risky code, and the problem if it happens.

Type cake when asked for a number, and Integer.parseInt stops the whole program with a NumberFormatException. That is harsh. Wrap the risky lines in a try block, then add a catch block for that kind of exception.

If all goes well, the catch block is skipped. If the exception happens, Java jumps from the problem line straight into catch, skipping the rest of try. Either way, the program carries on afterwards.

Inside catch, e is the exception itself, and explains what went wrong.

public class Main {
    public static void main(String[] args) {
        String[] typed = {"12", "cake", "7"};
        int total = 0;
        for (String text : typed) {
            try {
                total = total + Integer.parseInt(text);
                System.out.println("Added " + text);
            } catch (NumberFormatException e) {
                System.out.println("Skipped: " + e.getMessage());
            }
        }
        System.out.println("Total: " + total);
    }
}

Catch only the exceptions you expect, so real bugs still show up.