← Java from Scratch Lesson 53 of 88 · 10 XP

Multiple exceptions

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

One try can have several catch blocks, going from the specific to the general (otherwise the compiler says exception … has already been caught):

try {
    …
} catch (ArrayIndexOutOfBoundsException e) {
    …
} catch (ArithmeticException | NumberFormatException e) {    // multi-catch: one branch for several types
    System.out.println("bad data: " + e.getClass().getSimpleName());
} catch (Exception e) {                                     // everything else — at the end
    …
}

The hierarchy: Throwable → Exception → RuntimeException → (ArithmeticException, NullPointerException, …); and separately Error (OutOfMemoryError, StackOverflowError) — these aren't caught, they're problems of the JVM.

Task. Each line of the input is index divisor. The array is {10, 20, 30}; print arr[index] / divisor. Errors: a wrong index — no element; division by zero or not a number — bad data: <ClassName> (with a multi-catch and getClass().getSimpleName()).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.