Task 5 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 — throwing exceptions

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.

Throwing your own exceptions

You can throw an exception yourself to signal bad input, using throw new IllegalArgumentException("message"). This stops the method and hands the error to a caller's catch — a clean way to reject invalid arguments.


Worked example

static int checkAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("age cannot be negative");
    }
    return age;
}

If age is negative the method throws; otherwise it returns the age. A caller can wrap the call in try/catch to handle the rejection.


▶ Try it: run this — it checks each age and catches the rejection of the negative one.



To reject a bad argument, you write...


A throw statement...


Type exactly what this program prints.

int[] arr = {1, 2};
try {
    System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("out of range");
}

Throwing an exception for bad input is a way to...


True or false?