Java try/catch: Chaining catch Blocks, Multi-catch and finally (OCP 21)
Handling exceptions for the OCP 21 exam: try and catch syntax, ordering chained catch blocks, unreachable catches, multi-catch rules, finally execution order, return values and finally, exceptions thrown from finally, System.exit, wrapping causes and rethrowing.
kvi5hnuCode Sprout team member7 min readOn this page
The try statement separates code that might fail from code that recovers. The rules fit on one page, but the exam tests every edge: block order, which catch runs, when finally runs, and what a method returns when finally interferes.
The basic try/catch
try {
int seats = Integer.parseInt(input); // may throw
System.out.println("booked " + seats); // skipped if the line above throws
} catch (NumberFormatException e) {
System.out.println("not a number: " + input);
}
System.out.println("done"); // runs either way, once the exception is handled
When a statement in try throws, the rest of the try block is skipped and Java looks for a matching catch. If one matches, it runs, and execution continues after the whole try statement. If nothing in try throws, every catch is skipped.
Syntax rules:
| Rule | Example that breaks it |
|---|---|
| Braces are required, even for one statement | try x(); catch (Exception e) y(); doesn't compile |
A plain try needs at least one catch or a finally | try { x(); } alone doesn't compile |
The order is try, then catch blocks, then finally | try {} finally {} catch (Exception e) {} doesn't compile |
| A catch parameter is in scope only inside its own block | using e1 from the first catch in the second catch doesn't compile |
The exam uses the words "block" and "clause" interchangeably for catch and finally.
Chaining several catch blocks
Java checks the catch blocks from top to bottom and runs the first one whose type matches. At most one catch runs.
try {
book(request);
} catch (FileNotFoundException e) { // subclass first
System.out.println("missing file");
} catch (IOException e) { // then its superclass
System.out.println("I/O problem");
}
If a superclass catch comes before a subclass catch, the subclass block can never run. That's an unreachable code compile error ("exception FileNotFoundException has already been caught"). The pairs the exam relies on are:
IllegalArgumentExceptionbeforeNumberFormatExceptionIOExceptionbeforeFileNotFoundExceptionExceptionbefore anythingRuntimeExceptionbefore any runtime exception
Catching the same type twice is an error too. Unrelated types can appear in any order.
Remember the rule from article 66 as well. A catch for a checked exception the try can't throw doesn't compile.
Multi-catch
When several exceptions need the same handling, list them in one catch, separated by |:
String[] parts = "qty=abc".split("=");
try {
int qty = Integer.parseInt(parts[1]); // NumberFormatException here
System.out.println(parts[2] + qty); // or an index error here
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
System.out.println("bad order line: " + e.getClass().getSimpleName());
}
| Rule | Valid | Invalid |
|---|---|---|
| One variable name, at the end | catch (A | B e) | catch (A e | B e), catch (A e1 | B e2) |
| The alternatives must not be related by inheritance | IllegalStateException | IllegalArgumentException | FileNotFoundException | IOException, Exception | RuntimeException, A | A |
| The variable is implicitly final | catch (A | B e) { log(e); } | catch (A | B e) { e = new A(); } |
| The order within one multi-catch doesn't matter | B | A is the same as A | B | |
| Later catch blocks still can't be unreachable | catch (IllegalStateException | IllegalArgumentException e) {} catch (NumberFormatException e) {} |
Inside the block, the variable's type is the closest common supertype of the alternatives. For two runtime exceptions that's RuntimeException. A single-type catch parameter is not final, so catch (IllegalStateException e) { e = new IllegalStateException(); } compiles, though it's bad style.
finally
A finally block runs after the try block, and after the catch block if one ran. It runs whether or not an exception was thrown, and whether or not one was caught. That makes it the place for cleanup.

StringBuilder sb = new StringBuilder();
try {
sb.append("1");
} catch (Exception e) {
sb.append("2");
} finally {
sb.append("3");
}
sb.append("4");
System.out.println(sb); // 134
try { … } finally { … } with no catch is legal. The finally runs, and any exception continues to the caller afterwards.
finally and return
When try or catch executes return, the return value is computed and saved first, then finally runs, and then the method returns:
static int seatsLeft() {
int seats = 10;
try {
return seats; // 10 is saved
} finally {
seats = 0; // doesn't change the saved 10
}
} // returns 10
static StringBuilder ticket() {
StringBuilder sb = new StringBuilder("ticket");
try {
return sb; // the saved value is a reference
} finally {
sb.append("-VOID"); // the object it points to can still change
}
} // returns "ticket-VOID"
If finally itself executes return, that value replaces whatever try or catch was returning, and discards any exception in flight. The code compiles, but javac -Xlint warns that the finally clause cannot complete normally, because this hides bugs. Any statement after such a try statement is unreachable, which is a compile error.
int code() {
try { return 1; }
catch (Exception e) { return 2; }
finally { return 3; } // always returns 3 (with a lint warning)
}
finally can fail too
finally always starts, but it doesn't always finish. If code in finally throws, the rest of finally is skipped. The new exception replaces any exception that was already propagating, and the original is lost. (Try-with-resources handles this better with suppressed exceptions. See the next article.)
The one exception: System.exit
System.exit(status) stops the JVM immediately. If it's called in try or catch, the finally block does not run. A JVM crash or a killed process has the same effect, but System.exit is the case the exam asks about.
Wrapping and rethrowing
A catch block can throw a new exception that translates a low-level problem into one that makes sense for the caller. Pass the original as the cause so the stack trace isn't lost:
try {
loadSeats();
} catch (IOException e) {
throw new BookingFailedException("could not book", e); // e becomes getCause()
}
You can also simply rethrow the caught exception. Since Java 7, the compiler tracks a precise rethrow. If a catch (Exception e) parameter is never reassigned, throw e; is treated as throwing only the checked exceptions the try block can actually throw:
void rethrow() throws IOException { // IOException is enough, not Exception
try {
book(); // declares IOException
} catch (Exception e) {
log(e);
throw e;
}
}
If you assign to e inside the catch, the precise analysis is lost, and the method must declare Exception.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Java 22 allows an unnamed catch parameter,
catch (NumberFormatException _), when the exception object isn't used. It's on the Java 25 exam, not on 1Z0-830.
Exam traps from this article
A complete example
A theatre booking program. It traces which blocks run for each kind of failure, using chained catch blocks, a multi-catch and a finally. It then shows finally running for an uncaught exception, the saved-return-value rule, a finally that swallows or replaces an exception, wrapping with a cause, a precise rethrow, and finally System.exit skipping a finally block.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
public class Solution {
static class SoldOutException extends RuntimeException {
private static final long serialVersionUID = 1L;
SoldOutException(String show) { super(show + " is sold out"); }
}
static class BookingFailedException extends Exception {
private static final long serialVersionUID = 1L;
BookingFailedException(String message, Throwable cause) { super(message, cause); }
}
static void book(String request) throws IOException {
switch (request) {
case "sold-out" -> throw new SoldOutException("Hamlet");
case "bad-seat" -> Integer.parseInt("B12"); // NumberFormatException
case "no-file" -> throw new FileNotFoundException("seats.csv");
case "index" -> List.of("A1").get(4); // IndexOutOfBoundsException
case "disk" -> throw new IOException("disk full");
default -> { }
}
}
// Chained catch blocks: most specific first; at most one runs; finally always runs
static String handle(String request) {
StringBuilder trace = new StringBuilder("try");
try {
book(request);
trace.append(" ok");
} catch (FileNotFoundException e) { // subclass before IOException
trace.append(" catch-FNF");
} catch (IOException e) {
trace.append(" catch-IO");
} catch (NumberFormatException | IndexOutOfBoundsException e) { // multi-catch
trace.append(" catch-multi(").append(e.getClass().getSimpleName()).append(")");
} finally {
trace.append(" finally");
}
return trace.append(" after").toString();
}
// finally runs even when nothing catches the exception
static void uncaught(StringBuilder log) {
try {
log.append("try ");
throw new SoldOutException("Macbeth");
} finally {
log.append("finally ");
}
}
// The return value is computed before finally runs
static int seatsLeft() {
int seats = 10;
try {
return seats; // 10 is saved as the return value
} finally {
seats = 0; // too late to change the saved value
}
}
static StringBuilder ticket() {
StringBuilder sb = new StringBuilder("ticket");
try {
return sb; // the saved value is a reference...
} finally {
sb.append("-VOID"); // ...so changes to the object are visible
}
}
// A return in finally replaces the try's return AND discards its exception
@SuppressWarnings("finally") // javac -Xlint warns: finally clause cannot complete normally
static String swallow() {
try {
throw new SoldOutException("Othello");
} finally {
return "finally won";
}
}
// An exception from finally replaces the one from try
static void replaced() {
try {
throw new SoldOutException("Lear");
} finally {
Integer.parseInt("oops");
}
}
// Wrapping: translate a low-level exception and keep it as the cause
static void bookOrFail(String request) throws BookingFailedException {
try {
book(request);
} catch (IOException e) {
throw new BookingFailedException("could not book " + request, e);
}
}
// Precise rethrow: e is effectively final, so the compiler knows only IOException can escape
static void rethrow(String request) throws IOException {
try {
book(request);
} catch (Exception e) {
System.out.println(" logging " + e.getClass().getSimpleName() + " and rethrowing");
throw e;
}
}
public static void main(String[] args) {
System.out.println("1) chained catch blocks and multi-catch");
for (String r : List.of("ok", "no-file", "disk", "bad-seat", "index")) {
System.out.printf(" %-8s -> %s%n", r, handle(r));
}
try {
handle("sold-out"); // no catch matches: finally runs, then it propagates
} catch (SoldOutException e) {
System.out.println(" sold-out -> escaped handle(): " + e.getMessage());
}
System.out.println("2) finally always runs");
StringBuilder log = new StringBuilder();
try {
uncaught(log);
} catch (SoldOutException e) {
log.append("caller-catch");
}
System.out.println(" " + log);
System.out.println("3) finally and return values");
System.out.println(" seatsLeft() = " + seatsLeft() + ", ticket() = " + ticket());
System.out.println(" swallow() = " + swallow());
try {
replaced();
} catch (RuntimeException e) {
System.out.println(" replaced() threw " + e.getClass().getSimpleName() + ", the SoldOutException is lost");
}
System.out.println("4) wrapping and rethrowing");
try {
bookOrFail("no-file");
} catch (BookingFailedException e) {
System.out.println(" " + e.getMessage() + ", cause: " + e.getCause());
}
try {
rethrow("no-file");
} catch (IOException e) {
System.out.println(" caller got " + e);
}
System.out.println("5) System.exit skips finally");
try {
System.out.println(" exiting now");
System.exit(0);
} finally {
System.out.println(" this line never prints");
}
}
}
Output:
1) chained catch blocks and multi-catch
ok -> try ok finally after
no-file -> try catch-FNF finally after
disk -> try catch-IO finally after
bad-seat -> try catch-multi(NumberFormatException) finally after
index -> try catch-multi(IndexOutOfBoundsException) finally after
sold-out -> escaped handle(): Hamlet is sold out
2) finally always runs
try finally caller-catch
3) finally and return values
seatsLeft() = 10, ticket() = ticket-VOID
swallow() = finally won
replaced() threw NumberFormatException, the SoldOutException is lost
4) wrapping and rethrowing
could not book no-file, cause: java.io.FileNotFoundException: seats.csv
logging FileNotFoundException and rethrowing
caller got java.io.FileNotFoundException: seats.csv
5) System.exit skips finally
exiting now
Points to notice:
no-filematched theFileNotFoundExceptionblock.diskskipped it and matchedIOException, so ordering subclass-first made both reachable.- For
sold-out, no catch matched. Thefinallystill ran insidehandle, and then the exception escaped tomain. seatsLeft()returned 10 even thoughfinallysetseatsto 0, whileticket()showed the-VOIDadded infinally.swallow()needed@SuppressWarnings("finally")to compile without a lint warning. ItsSoldOutExceptionsilently disappeared.- The precise rethrow let
rethrowdeclare onlyIOExceptionwhile catchingException. - "this line never prints" never printed, because
System.exitended the JVM beforefinallycould run.
Common questions
Should I catch Exception at all?
At the top of an application, such as main or a request handler, to log and keep running, yes. Deep inside business code, catch specific types. Catching too broadly hides bugs.
Is an empty catch block legal?
Yes, catch (Exception e) { } compiles. It quietly swallows the problem, so real code should at least log it.
Does finally run if the catch block itself throws?
Yes. finally runs, and then the exception from the catch propagates, unless finally replaces it.
Summary
tryneeds braces, followed by one or morecatchblocks and/or afinally.- Chained catch blocks are checked in order, and at most one runs. Put subclasses before superclasses.
- Multi-catch:
catch (A | B e)with unrelated types and a final variable. finallyalways runs, except afterSystem.exit. A return value is saved before it runs, and areturnor exception fromfinallywins.- Wrap exceptions with a cause, and rethrow precisely with an effectively final catch parameter.
Practice quiz
Test yourself with the try, catch and finally quiz: 10 exam-style questions with explanations.
Previous: Java Common Exception Classes: Runtime, Checked and Error Types on the Exam (OCP 21)
Next: Java try-with-resources: AutoCloseable, Closing Order and Suppressed Exceptions (OCP 21)
Related reading
- Java Common Exception Classes: Runtime, Checked and Error Types on the Exam (OCP 21)
- Java Exceptions: Checked vs Unchecked, the Throwable Hierarchy and Overriding Rules (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- Java 2D Rendering Pipeline: Shapes, Paths and Constructive Area Geometry

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.