Sub topic 5
Handling Several Exception Types
One block of code can fail in more than one way. Say you read a number from text and then divide by it. The text might not be a number, or the number might be zero. Each problem throws a different exception, and you may want to handle each one differently.
Java gives you two tools for this:
- Multiple catch blocks. You write several
catchblocks after onetry, one for each exception type. - Multi-catch. You write one
catchblock that names several types joined with|.
Multiple catch blocks
When an exception is thrown, Java checks the catch blocks from top to bottom. The first block whose type matches the exception runs. Java skips all the others.
public class SeveralCatches {
static int parseAndDivide(String text, int divisor) {
try {
int n = Integer.parseInt(text);
return n / divisor;
} catch (NumberFormatException e) {
System.out.println("Bad number: " + text);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
return 0;
}
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
Bad number: ten
0
Cannot divide by zero
0Each problem gets its own message. The program keeps running in every case.
Order matters: specific before general
A catch block matches its own type and every subclass of that type. catch (Exception e) matches almost everything. So put the most specific types first and the general types last:
public class CatchOrder {
public static void main(String[] args) {
try {
int n = Integer.parseInt("abc");
System.out.println(n);
} catch (NumberFormatException e) {
System.out.println("Specific: not a number");
} catch (Exception e) {
System.out.println("General: something else went wrong");
}
}
}If you swap the two blocks, the code will not compile. The compiler sees that NumberFormatException was already caught by Exception, so the second block could never run.
Multi-catch: one block, several types
Sometimes two exceptions need exactly the same handling. Writing two identical blocks is repetitive. A multi-catch clause lists the types separated by a vertical bar |:
public class MultiCatchDemo {
static int parseAndDivide(String text, int divisor) {
try {
int n = Integer.parseInt(text);
return n / divisor;
} catch (NumberFormatException | ArithmeticException e) {
System.out.println("Could not compute: " + e);
return 0;
}
}
public static void main(String[] args) {
System.out.println(parseAndDivide("ten", 2));
System.out.println(parseAndDivide("10", 0));
}
}Output:
Could not compute: java.lang.NumberFormatException: For input string: "ten"
0
Could not compute: java.lang.ArithmeticException: / by zero
0The variable e holds whichever exception was thrown.
Which one to use
| Situation | Use | Column |
|---|---|---|
| Each exception needs different handling | Separate catch blocks | |
| Several exceptions need the same handling | Multi-catch with `\ | ` |
| A specific case plus a fallback for everything else | Specific catch first, general catch last |
Exercise
A try block can throw NumberFormatException or NullPointerException, and you want to print the same message for both. Write the catch line. Then explain why catch (Exception e) placed above catch (NullPointerException e) causes a compile error.
Show answer
Use catch (NumberFormatException | NullPointerException e). Putting Exception first fails because NullPointerException is a subclass of Exception. The first block would always catch it, so the second block could never run, and the compiler rejects code that can never run.
Exercise
Why does catch (NumberFormatException | IllegalArgumentException e) fail to compile, and how do you fix it?
Show answer
NumberFormatException is a subclass of IllegalArgumentException, so the second type already covers the first. Multi-catch does not allow types that are related this way. Fix it by writing only catch (IllegalArgumentException e).