11.2 try-catch-finally Blocks & Program Flow Alteration
Key Takeaways
A classic try block requires at least one catch block or a finally block (or both), and curly braces are mandatory on every try, catch, and finally block
A broader catch cannot precede a catch whose alternatives it already handles. A specific checked catch must be reachable under Java’s exception analysis, with special treatment for Exception and its supertypes.
Multi-catch alternatives cannot be subtypes of each other. The shared parameter is implicitly final.
When control leaves the try block or a selected catch in ordinary execution, finally runs before control continues. A block that never exits or a successful JVM shutdown may never reach finally.
An abrupt transfer from finally can replace a pending return or exception. Reassigning a local in a normally completing finally leaves a previously evaluated return value intact.
try-catch-finally Blocks & Program Flow Alteration
Independent prep covering try-catch-finally syntax and control-flow alteration in Official Domain 8 (Handling Exceptions). On the 1Z0-808 exam, try-catch-finally questions rarely involve complicated business logic—instead, they pack subtle compiler rejections (block order, unreachable checked catches, multi-catch rules) and execution-order twists (exceptions thrown inside catch, return statements inside try and finally, and System.exit) into 15-line snippets.
Valid try Block Forms & Mandatory Braces
Unlike if, else, for, or while, curly braces {} are always mandatory on try, catch, and finally blocks—even when a block contains only a single statement. Omitting braces fails compilation immediately.
For traditional exception handling (without Java 7+ try-with-resources), a try block must be paired with at least one catch block, a finally block, or both:
| Syntax Form | Valid? | Notes |
|---|---|---|
try { ... } catch (Exception e) { ... } | Valid | Handles matching exceptions; no finally cleanup block |
try { ... } finally { ... } | Valid | Runs finally cleanup without catching exceptions |
try { ... } catch (Exception e) { ... } finally { ... } | Valid | Zero or more catch blocks in order, followed by one optional finally |
try { ... } (bare try alone) | Does Not Compile | Missing catch or finally |
try { ... } finally { ... } catch (Exception e) { ... } | Does Not Compile | finally must come after all catch blocks |
Multiple catch Ordering & Unreachable Checked Catches
When an exception is thrown inside a try block, the JVM scans the attached catch clauses from top to bottom and enters at most one catch block—the first one with a parameter type, or multi-catch alternative, compatible with the thrown object’s runtime class.
Subclass Must Precede Superclass
Because the first matching catch wins, placing a superclass before a subclass makes the subclass catch permanently unreachable, which javac rejects with exception <Subclass> has already been caught:
import java.io.FileNotFoundException;
import java.io.IOException;
public class CatchOrder {
static void open() throws IOException {
throw new FileNotFoundException("missing.txt");
}
public static void main(String[] args) {
try {
open();
} catch (FileNotFoundException e) { // Subclass FIRST -> compiles!
System.out.println("Specific file missing");
} catch (IOException e) { // Superclass SECOND -> compiles!
System.out.println("General I/O failure");
}
}
}
If you swap those two catch blocks so catch (IOException e) precedes catch (FileNotFoundException e), compilation fails. Unrelated sibling classes—such as FileNotFoundException and EOFException (both direct subclasses of IOException)—can appear in either order.
Unreachable Checked catch Rule
A classic 1Z0-808 compiler trap involves catching a checked exception when nothing in the try block can possibly throw it:
import java.io.IOException;
public class UnreachableChecked {
void noChecked() {
System.out.println("Safe");
}
void test() {
// try { noChecked(); } catch (IOException e) {} // DOES NOT COMPILE: IOException is never thrown
try { noChecked(); } catch (Exception e) {} // Compiles: Exception is exempt from the specific checked-catch rule
try { noChecked(); } catch (RuntimeException e) {} // Compiles here: unchecked, with no earlier related catch
try { noChecked(); } catch (Throwable t) {} // Compiles: Throwable is exempt from the specific checked-catch rule
}
}
Watch one subtle nuance: if a method in the try block declares throws Exception, then catch (IOException e) does compile, because such a method could throw an IOException. That handler alone does not handle all possible checked Exceptions declared by the call. An additional handler or throws clause must account for the remainder.
Java 7/8 Multi-Catch Blocks
Java SE 7 introduced multi-catch to avoid duplicating identical handler bodies across unrelated exception types. Multi-catch obeys three strict syntax and semantic rules:
- No inheritance relationship allowed — None of the exception types separated by
|may be a subclass of another in the samecatchclause. Writingcatch (FileNotFoundException | IOException e)fails compilation becauseFileNotFoundExceptionextendsIOException. - Single parameter identifier at the end — Write
catch (IOException | SQLException e), nevercatch (IOException e1 | SQLException e2)orcatch (IOException e | SQLException e). - The multi-catch parameter is implicitly
final— Inside a multi-catch block, reassigningefails compilation, whereas a single-type catch parameter can be reassigned if it is not declared final:
import java.io.IOException;
import java.sql.SQLException;
public class MultiCatchRules {
static void run(boolean io) throws IOException, SQLException {
if (io) throw new IOException();
throw new SQLException();
}
public static void main(String[] args) {
try {
run(true);
} catch (IOException | SQLException e) {
// e = new RuntimeException(); // DOES NOT COMPILE: multi-catch parameter e may not be assigned
System.out.println(e.getClass().getSimpleName());
}
try {
run(false);
} catch (Exception e) {
e = new RuntimeException("reassigned"); // Compiles in single-type catch
System.out.println(e.getMessage());
}
}
}
finally Execution Guarantees & Control-Flow Traps
In ordinary Java execution, the finally block runs when control exits the try block or the selected catch. It covers these paths:
trycompletes normally without throwing,trythrows an exception that acatchblock handles,trythrows an exception with no matchingcatchblock, ortryorcatchexecutes areturn,break, orcontinuestatement.
When is finally skipped? If a block never exits, its finally has not been reached. Successful JVM shutdown or forced termination may also end execution before cleanup runs.
public class ExitSkipsFinally {
public static void main(String[] args) {
try {
System.out.print("A");
System.exit(0);
} finally {
System.out.print("B"); // Never executes!
}
}
}
Assuming the exit request is permitted and shutdown succeeds, the program prints only A. In Java SE 8 a security manager can reject the call with SecurityException; that is an ordinary Java exception and does run finally as control leaves the try.
Tracing Exceptions Thrown Inside catch or finally
A catch block is not protected by its sibling catch blocks. If catch throws a new exception, other catch blocks on the same try do not catch it; instead, finally executes and the new exception propagates outward:
public class CatchThrows {
public static void main(String[] args) {
StringBuilder trace = new StringBuilder();
try {
trace.append("1");
throw new IllegalArgumentException();
} catch (IllegalArgumentException e) {
trace.append("2");
throw new NullPointerException();
} catch (RuntimeException e) {
trace.append("3"); // Never reached: sibling catch cannot catch exception from previous catch
} finally {
trace.append("4");
}
// In this execution, NullPointerException propagates out of main.
}
}
Before NullPointerException escapes main, trace becomes "124"—"3" is never appended.
The Classic finally Return & Mutation Traps
The exam loves testing what happens when try, catch, and finally interact with return values:
public class FinallyReturnTraps {
static int overrideReturn() {
try {
return 1;
} finally {
return 2; // Overrides try's return (and would swallow any exception from try!)
}
}
static int primitiveSavedBeforeFinally() {
int x = 1;
try {
return x; // Value 1 is evaluated and saved before finally executes
} finally {
x = 2; // Modifies local x, NOT the saved return value
}
}
static StringBuilder referenceObjectMutated() {
StringBuilder sb = new StringBuilder("a");
try {
return sb; // Reference to the StringBuilder object is saved
} finally {
sb.append("b"); // Mutates the SAME heap object -> caller sees "ab"!
sb = new StringBuilder("c"); // Reassigns local variable only -> caller still sees "ab"
}
}
public static void main(String[] args) {
System.out.println(overrideReturn()); // Prints 2
System.out.println(primitiveSavedBeforeFinally()); // Prints 1
System.out.println(referenceObjectMutated()); // Prints ab
}
}
Caution
When finally itself completes abruptly, its reason replaces the earlier transfer. A throw caught within finally does not replace a pending transfer if finally then completes normally. For instance, try { throw new RuntimeException("boom"); } finally { return; } returns normally without throwing any exception at all—whereas try { return 1; } finally { throw new IllegalStateException(); } discards 1 and propagates IllegalStateException.
What is the result of compiling and running the following code?
static int compute() {
int value = 10;
try {
return value;
} finally {
value = 20;
}
}
It fails to compile because finally modifies a variable used in return
It compiles and returns 20 because finally executes after try
It compiles and returns 10 because the primitive return value is saved before finally runs
It compiles and throws an IllegalStateException
Which catch clause is illegal even with a reachable try body that can throw all the named checked types? Consider each option independently with no earlier handler.
catch (FileNotFoundException | IOException e)
catch (IOException | SQLException e)
catch (ArithmeticException | NullPointerException e)
catch (RuntimeException e) following a try block that calls only System.out.println("ok")
Given a try block whose body contains only String s = "java";, which catch handler compiles cleanly?
catch (IOException e) {}
catch (java.text.ParseException e) {}
catch (ClassNotFoundException e) {}
catch (Exception e) {}
Sections you finish are checked off in the contents.