Real code may meet several kinds of exceptions, and must often release resources whether or not an error occurs. Java provides structures for both.
Multiple catch Statements
A try block may be followed by several catch blocks, each for a different exception type. When an exception occurs, the catch blocks are tested in order, and the first one whose type matches (or is a superclass of the exception) runs; the others are skipped. Subclass exceptions must be caught before their superclasses: if catch (Exception e) came first, it would catch everything and the later blocks would be unreachable, which is a compile error. Since Java 7, one catch can handle several unrelated types with a multi-catch: catch (ArithmeticException | NumberFormatException e).
Definition: finally block. A block following try or catch whose statements are always executed, whether or not an exception occurs, typically used to release resources.
Nested try Statements
A try block can be placed inside another try block. If an exception in the inner try is not caught by an inner catch, it is passed to the outer try's catch blocks. If none of them matches, it goes further out, to the calling method, and finally to the JVM. Nested try is useful when part of a task can fail on its own and should be handled locally, while other errors are handled at a higher level.
The finally Block
A finally block follows the try (and catch) blocks and always executes: when the try block completes normally, when an exception is caught, and even when an exception is not caught or a return statement is executed. It is used to release resources, such as closing files, network connections and database connections. A try must have at least one catch or a finally. Since Java 7, try-with-resources, try (Scanner sc = new Scanner(...)) { ... }, closes the resource automatically.
Order of Execution
If no exception occurs: try completes, catch blocks are skipped, finally runs, and execution continues. If an exception occurs and is caught: try stops at that point, the matching catch runs, then finally, then execution continues. If it is not caught: finally runs, and then the exception passes to the caller.
Table 4.4: Flow through try, catch and finally
| Case | Blocks that run | Then |
|---|---|---|
| No exception | try, finally | Continue after |
| Exception caught | try (part), catch, finally | Continue after |
| Exception not caught | try (part), finally | Passed to caller |
Example 4.4: Multiple catch with finally
Problem: For each input in {"10", "abc", "0"}, convert it to an int n, compute q = 50 / n, and store q in an array of size 3 at index 5 if q > 4 (else at 0). Show which catch runs, and that finally always runs. Then show a nested try.
Solution:
- "10": q = 5, so the store uses index 5, and ArrayIndexOutOfBoundsException is caught; finally runs.
- "abc": parseInt throws NumberFormatException, caught; finally runs.
- "0": 50 / 0 throws ArithmeticException before the store, caught; finally runs.
- In the nested try, the inner catch handles only ArithmeticException, so the bad index passes to the outer catch.
Result: Each case is handled by the right catch block, finally runs three times, and the outer try handles the nested exception.
public class MultiCatch {
public static void main(String[] args) {
String[] inputs = {"10", "abc", "0"};
int[] store = new int[3];
for (String s : inputs) {
try {
int n = Integer.parseInt(s);
int q = 50 / n;
store[q > 4 ? 5 : 0] = q; // index 5 is out of bounds
System.out.println("stored " + q);
} catch (NumberFormatException e) {
System.out.println("'" + s + "' is not a number");
} catch (ArithmeticException e) {
System.out.println("division by zero for '" + s +
"'");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("bad index: " + e.getMessage());
} finally {
System.out.println(" finally ran for '" + s + "'");
}
}
try {
try {
int[] a = new int[2];
a[2] = 1;
} catch (ArithmeticException e) {
System.out.println("inner catch");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("outer catch handled it");
}
}
}
Output
bad index: Index 5 out of bounds for length 3
finally ran for '10'
'abc' is not a number
finally ran for 'abc'
division by zero for '0'
finally ran for '0'
outer catch handled it
Common mistakes
- Catching Exception before its subclasses, which makes the later catches unreachable.
- Putting important clean-up code after the try instead of in finally.
- Assuming finally does not run when there is a return in the try block.
Key takeaways
- Several catch blocks are tested in order; put subclasses first.
- An exception not caught by an inner try goes to the outer try.
- finally always runs and is used to release resources.
- try-with-resources closes resources automatically.
Practice questions
- In what order should catch blocks for a subclass and its superclass appear?
- When does a finally block run?
- What happens to an exception not caught in an inner try?
Answers to the practice questions
- The subclass catch must come before the superclass catch.
- Always, whether or not an exception occurs or is caught.
- It is passed to the catch blocks of the outer try.
Sources
- Official BCA syllabus Object Oriented Programming using Java, course code 25BCA402SEC01, Unit IV
