Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

(Optional) 6.5 Exceptions — try and catch

Lesson

Optional lesson — beyond the AP CS A exam. Catching exceptions with try/catch is not on the AP exam (which only declares throws); this is here for a fuller picture of Java.

Handling errors with try/catch

Some operations can fail at run time — dividing by zero, or reading past the end of an array. These throw an exception, which normally stops the program. A try/catch block lets you handle the error: put the risky code in try, and the recovery code in catch.


Worked example

try {
    int result = 100 / x;
    System.out.println(result);
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}

If x is 0, the division throws an ArithmeticException, and the catch block runs instead of crashing. e.getMessage() describes what went wrong.


▶ Try it: run this — it divides 100 by each value and catches the division by zero.



The risky code goes in the...


The recovery code goes in the...


Type exactly what this program prints.

int x = 0;
try {
    System.out.println(10 / x);
} catch (ArithmeticException e) {
    System.out.println("oops");
}

e.getMessage() returns...


True or false?