Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 06 / Topic 3 of 8

Several ways to go wrong, several catch blocks

One try block can be followed by several catch blocks, one per exception type you expect. Java checks them top to bottom and runs the first one that matches.

try {
    withdraw(amountText, balances, slot);
} catch (NumberFormatException e) {
    System.out.println("  Amount is not a number: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("  Unknown account slot: " + e.getMessage());
}

Order matters. NumberFormatException is a subtype of Exception, so a wider catch (Exception e) placed before a narrower one would always match first, and the narrower block could never run. The compiler catches this mistake for you:

error: exception NumberFormatException has already been caught

(Try moving catch (Exception e) above catch (NumberFormatException e) for Case 1 in examples/02_multi_catch_demo.java to see this for yourself.) The rule: list the most specific exception types first, and a catch-all like catch (Exception e) last, if you use one at all.

Multi-catch. When two unrelated exception types should be handled the same way, combine them with | in one catch:

} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
    System.out.println("  Bad input: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}

e.getClass().getSimpleName() prints which of the two actually happened, since one catch now covers both.

Real output (examples/02_multi_catch_demo.java):

$ javac 02_multi_catch_demo.java
$ java MultiCatchDemo
Case 1: bad amount text
  Amount is not a number: For input string: "abc"
Case 2: unknown account slot
  Unknown account slot: Index 5 out of bounds for length 2
Case 3: amount text or slot error, handled together
  Bad input: NumberFormatException: For input string: "xyz"
Case 4: amount is zero (ArithmeticException)
  Cannot divide by zero amount: / by zero
Done.

Full program: examples/02_multi_catch_demo.java.

Done here? The practice set for Part 6 — including the solutions — is on the part page.

Search the guide