Sub topic 5
Handling Several Exception Types
A single block of code can fail in more than one way. Suppose a line reads a value from an array, turns it into a number, and divides by it. The array index might be wrong. The text might not be a number. The number might be zero. Each problem throws a different exception.
This chapter shows two ways to handle several exception types around one try block:
- Multiple catch blocks. You write one
catchper exception type, and each one does its own thing. - Multi-catch. One
catchhandles several types with the same code.
Why one catch block is often not enough
Each type of failure usually needs a different response. A missing value might mean "ask the user again." Bad text might mean "show an error message." Dividing by zero might mean "use a default." If you lump them all together, you lose the chance to react correctly.
Writing multiple catch blocks
You can put as many catch blocks after a try as you need. Each one names the exception type it handles.
public class SeveralCatches {
static void process(String[] values, int index) {
try {
String text = values[index];
int n = Integer.parseInt(text);
System.out.println("100 / " + n + " = " + (100 / n));
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No value at index " + index);
} catch (NumberFormatException e) {
System.out.println("Not a number: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
public static void main(String[] args) {
String[] values = {"5", "abc", "0"};
process(values, 0);
process(values, 1);
process(values, 2);
process(values, 7);
}
}Running it prints:
100 / 5 = 20
Not a number: For input string: "abc"
Cannot divide by zero
No value at index 7Each call fails in a different place, or not at all, and a different catch block runs each time.
How Java picks a catch block
When an exception is thrown inside the try, Java stops running the rest of the try block. It then checks the catch blocks from top to bottom. The first block whose type matches the exception runs. A block matches if the exception is that type or a subclass of it. A subclass is a class that extends another class, so it counts as a more specific kind of that class.
Only one catch block ever runs for a single exception. After it finishes, the program continues after the whole try/catch statement. If no block matches, the exception keeps travelling up to the method that called this one.
Order matters: specific before general
Some exception types are subclasses of others. For example, NumberFormatException extends IllegalArgumentException, which extends RuntimeException. A catch (RuntimeException e) block would therefore also catch a NumberFormatException.
So put the most specific type first and the most general type last. Here a general block acts as a fallback:
public class CatchOrder {
public static void main(String[] args) {
String[] inputs = {"12", "twelve", null};
for (String input : inputs) {
try {
int age = Integer.parseInt(input.trim());
System.out.println("Age: " + age);
} catch (NumberFormatException e) {
System.out.println("Not a whole number: " + input);
} catch (RuntimeException e) {
System.out.println("Something else went wrong: "
+ e.getClass().getSimpleName());
}
}
}
}Output:
Age: 12
Not a whole number: twelve
Something else went wrong: NullPointerExceptionCalling input.trim() on null throws a NullPointerException. That type is not a NumberFormatException, so the second block catches it.
If you swap the two blocks, with RuntimeException first, the code will not compile. The general block would catch everything, and the specific block below it could never run. Java treats that unreachable block as a mistake:
error: exception NumberFormatException has already been caughtMulti-catch: one block for several types
Sometimes two different exceptions need exactly the same handling. Writing the same code twice is tedious and easy to get wrong. Since Java 7, you can list several types in one catch, separated by a vertical bar |. This is called multi-catch.
public class MultiCatchDemo {
static int parseAndDivide(String text, int divisor) {
try {
return Integer.parseInt(text) / divisor;
} catch (NumberFormatException | ArithmeticException e) {
System.out.println("Could not compute: " + e.getClass().getSimpleName());
return -1;
}
}
public static void main(String[] args) {
System.out.println(parseAndDivide("10", 2));
System.out.println(parseAndDivide("ten", 2));
System.out.println(parseAndDivide("10", 0));
}
}Output:
5
Could not compute: NumberFormatException
-1
Could not compute: ArithmeticException
-1The block runs if the exception is a NumberFormatException or an ArithmeticException. Inside the block, e holds whichever one was actually thrown.
Rules for multi-catch
Multi-catch has three rules that beginners often run into.
- The types cannot be related by subclassing. You cannot write
NumberFormatException | IllegalArgumentException, because the first is already a kind of the second. Listing both adds nothing. The compiler says:
``text error: Alternatives in a multi-catch statement cannot be related by subclassing ``
The fix is to keep only the more general type, IllegalArgumentException.
- The variable
eis final. In a multi-catch block, you cannot assign a new value toe. Writinge = null;giveserror: multi-catch parameter e may not be assigned. You rarely need to reassign it anyway.
- You can only use methods the types share. Java does not know in advance which type
ewill hold, so it treatseas their closest common parent class. ForNumberFormatException | ArithmeticException, that parent isRuntimeException. Methods such asgetMessage()andgetClass()work, because every exception has them.
Choosing between the two styles
| Situation | Use |
|---|---|
| Each failure needs a different response | Separate catch blocks |
| Several failures need the exact same response | Multi-catch |
| You want a fallback for anything unexpected | A general catch block placed last |
| One type is a subclass of another and both need the same handling | Catch only the parent type |
Common mistakes
- General type first. This causes a compile error. Put specific types above general ones.
- Related types in one multi-catch. This also causes a compile error. Keep only the parent type.
- Expecting more than one catch to run. Only the first matching block runs.
- Copying the same code into several catch blocks. If the bodies are identical, combine them with
|.
Exercises
Exercise
A try block has catch (IllegalArgumentException e) first and catch (NumberFormatException e) second. What happens when you compile it, and how do you fix it?
Show answer
It does not compile. NumberFormatException is a subclass of IllegalArgumentException, so the first block already catches it, and the compiler reports "exception NumberFormatException has already been caught". Fix it by putting the NumberFormatException block first, or by deleting it if both need the same handling.
Exercise
Rewrite these two blocks as one: catch (ArrayIndexOutOfBoundsException e) { System.out.println("Bad input"); } and catch (ArithmeticException e) { System.out.println("Bad input"); }.
Show answer
catch (ArrayIndexOutOfBoundsException | ArithmeticException e) { System.out.println("Bad input"); }. This is allowed because neither type is a subclass of the other.
Exercise
In SeveralCatches, what does process(new String[] {"4"}, 0) print, and why don't any catch blocks run?
Show answer
It prints "100 / 4 = 25". No exception is thrown, so Java skips every catch block and continues after the try/catch statement.
Exercise
Why does catch (NumberFormatException | IllegalArgumentException e) fail to compile, while catch (NumberFormatException | ArithmeticException e) compiles?
Show answer
NumberFormatException extends IllegalArgumentException, and multi-catch alternatives cannot be related by subclassing. NumberFormatException and ArithmeticException are separate branches under RuntimeException, so neither is a subclass of the other.