Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to catch multiple exceptions

Short answer

Add several catch blocks — the first matching one runs:

void parseAndPrint(String[] parts, int index) {
    try {
        int value = Integer.parseInt(parts[index]);
        IO.println("Value: " + value);
    } catch (NumberFormatException e) {
        IO.println("Not a number: " + parts[index]);
    } catch (ArrayIndexOutOfBoundsException e) {
        IO.println("No element " + index);
    }
}
 
void main() {
    String[] parts = {"10", "abc"};
    parseAndPrint(parts, 0);
    parseAndPrint(parts, 1);
    parseAndPrint(parts, 5);
}

Output:

Value: 10
Not a number: abc
No element 5

One handler for several types

If the reaction is the same, list the types separated by |:

void main() {
    for (String input : List.of("42", "x", "")) {
        try {
            IO.println(100 / Integer.parseInt(input.isEmpty() ? "0" : input));
        } catch (NumberFormatException | ArithmeticException e) {
            IO.println("Bad input: " + e.getClass().getSimpleName());
        }
    }
}

Output:

2
Bad input: NumberFormatException
Bad input: ArithmeticException

Block order

Put more specific exceptions before general ones. Otherwise the compiler reports that a block is unreachable:

void main() {
    try {
        Integer.parseInt("x");
    } catch (Exception e) {
        IO.println("general");
    } catch (NumberFormatException e) {
        IO.println("number");
    }
}

Output:

Main.java:6: error: exception NumberFormatException has already been caught

finally

The finally block always runs — after successful code and after an exception:

void main() {
    try {
        IO.println("working");
        throw new IllegalStateException("boom");
    } catch (IllegalStateException e) {
        IO.println("caught " + e.getMessage());
    } finally {
        IO.println("cleanup");
    }
}

Output:

working
caught boom
cleanup

Common mistake

Catching Exception and silently ignoring it. The error disappears, and the program keeps working with bad data:

void main() {
    int total = 0;
    for (String s : List.of("5", "five", "7")) {
        try {
            total += Integer.parseInt(s);
        } catch (Exception e) {
        }
    }
    IO.println(total);
}

Output:

12

At the very least, log the error or tell the user which data was skipped.

Functions used in this recipe

  • try / catch / finally — Catches exceptions; finally always runs, and try-with-resources closes resources for you.

Thanks for reading!

Donate to the site — we work hard for you.