Task 3 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 — multiple catches and finally

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.

Several catches and finally

Different problems throw different exception types, and you can write a separate catch for each. A finally block, if present, runs no matter what — whether or not an exception happened — so it is used for cleanup.


Worked example

try {
    int n = Integer.parseInt(text);
    System.out.println(n);
} catch (NumberFormatException e) {
    System.out.println("Not a number");
} finally {
    System.out.println("Done");
}

If text is not a number, parseInt throws a NumberFormatException. Either way, finally prints Done.


▶ Try it: run this — it parses each input and always prints a Done line from finally.



A finally block runs...


Integer.parseInt("oops") throws a...


Type exactly what this program prints.

String[] in = {"5", "no"};
for (int i = 0; i < in.length; i++) {
    try {
        System.out.println("Parsed: " + Integer.parseInt(in[i]));
    } catch (NumberFormatException e) {
        System.out.println("Bad: " + in[i]);
    } finally {
        System.out.println("Done " + in[i]);
    }
}

For different error types, you can have...


True or false?