try, catch and finally Flow Puzzles
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A classic output round shows a try, catch and finally with a return or a throw inside and asks what prints and what comes back. The interviewer is checking that you know the exact order, and which value or exception survives.
return in try and finally: which value wins
finally is a block after try and catch that runs on every way out of them: normal end, return, break or an exception. It is skipped only when the JVM stops, for example after System.exit.
Three methods return from try, from finally and from catch. Each prints a note from finally, so you can see when it runs compared with the return.
Example 1 · Which return wins?
public class ReturnFinallyDemo { static int tryReturns() { try { return 1; } finally { System.out.println("(finally runs before the caller gets 1)"); } }
@SuppressWarnings("finally") static int finallyReturns() { try { return 1; } finally { return 2; } }
static String afterCatch() { try { throw new IllegalStateException("bad state"); } catch (IllegalStateException e) { return "catch"; } finally { System.out.println("(finally after catch)"); } }
public static void main(String[] args) { System.out.println("tryReturns: " + tryReturns()); System.out.println("finallyReturns: " + finallyReturns()); System.out.println("afterCatch: " + afterCatch()); }}(finally runs before the caller gets 1) tryReturns: 1 finallyReturns: 2 (finally after catch) afterCatch: catch
What this code does
- The method call inside
printlnfinishes first, so the finally message prints on its own line before "tryReturns: 1". - A
returnin finally overrides the try's return value; the catch's return value is saved while finally runs.
When try runs return x;, Java evaluates and saves x, runs finally, and only then returns the saved value. A return inside finally replaces it and cancels any exception on its way out. The rules:
try { return 1; } finally { print }prints, then returns 1.try { return 1; } finally { return 2; }returns 2;javac -Xlintwarns "finally clause cannot complete normally".finallyalso runs afterbreak,continueor an exception.- It does not run if the JVM stops:
System.exit, a crash or a killed process.
Predict the output
Which value comes back?
Read each program and pick what it prints.
Round 1 of 3
A return in try, a print in finally.
finally changing a returned primitive vs an object
The saved return value is the value of return x that Java captures before finally runs. For a primitive it is a copy of the number; for an object it is a copy of the reference.
Four methods return a number, a StringBuilder and an array while finally tries to change them. Predict which changes the caller can see.
Example 2 · finally can change an object, not a saved primitive
public class FinallyChangeDemo { static int marks() { int m = 50; try { return m; } finally { m = 100; } }
static StringBuilder remark() { StringBuilder sb = new StringBuilder("Pass"); try { return sb; } finally { sb.append(" with distinction"); } }
static StringBuilder replaced() { StringBuilder sb = new StringBuilder("Pass"); try { return sb; } finally { sb = new StringBuilder("Fail"); } }
static int[] scores() { int[] a = {1, 2}; try { return a; } finally { a[0] = 99; } }
public static void main(String[] args) { System.out.println(marks()); System.out.println(remark()); System.out.println(replaced()); System.out.println(scores()[0]); }}50 Pass with distinction Pass 99
What this code does
- The saved value for
marks()is the number 50, so changingmlater has no effect. - For objects, the saved value is a reference: changing the object (
append,a[0] = 99) shows in the result, but pointingsbat a new object does not.
finally can change the object that the saved reference points to, for example sb.append(...) or a[0] = 99, and the caller sees it. Pointing the variable at a new object does not change what is returned.
Order of execution
try { return m; } finally { m = 100; }
Tap the steps in the order Java runs them.
Exceptions thrown in catch and in finally: what is lost
A lost exception is an exception that disappears because finally throws a new one or returns. The original is replaced and leaves no trace in the stack trace.
Four cases of what survives: finally throws, finally returns, catch wraps the original as a cause, and try-with-resources closes a failing resource.
Example 3 · Lost, wrapped and suppressed exceptions
class Resource implements AutoCloseable { @Override public void close() { throw new IllegalStateException("close failed"); }}
public class LostExceptionDemo { static void finallyThrows() { try { throw new IllegalStateException("original"); } finally { throw new RuntimeException("from finally"); } }
@SuppressWarnings("finally") static String finallyReturns() { try { throw new IllegalStateException("original"); } finally { return "exception swallowed"; } }
static void catchWraps() { try { Integer.parseInt("abc"); } catch (NumberFormatException e) { throw new IllegalArgumentException("bad marks", e); } finally { System.out.println("finally still runs"); } }
public static void main(String[] args) { try { finallyThrows(); } catch (RuntimeException e) { System.out.println("1: caught " + e.getMessage()); }
System.out.println("2: " + finallyReturns());
try { catchWraps(); } catch (IllegalArgumentException e) { System.out.println("3: caught " + e.getMessage() + ", cause " + e.getCause().getClass().getSimpleName()); }
try (Resource r = new Resource()) { throw new RuntimeException("body failed"); } catch (RuntimeException e) { System.out.println("4: caught " + e.getMessage() + ", suppressed " + e.getSuppressed()[0].getMessage()); } }}1: caught from finally 2: exception swallowed finally still runs 3: caught bad marks, cause NumberFormatException 4: caught body failed, suppressed close failed
What this code does
- 1 and 2: an exception or return from finally replaces the "original" exception, which is lost with no trace.
- 3: passing
eas the cause keeps the original. 4: try-with-resources keeps the body's exception and attaches the close failure as suppressed.
If catch throws a new exception, finally still runs and then the new exception leaves the method. Pass the original as the cause, new X("msg", e), so it stays in the stack trace. In try-with-resources the body's exception wins and the close() failure is kept as suppressed.
Revise: Exception chaining (opens in a new tab) and Suppressed exceptions (opens in a new tab).
Find the bug
Where does the exception go?
Tap the line that loses the error.
Support cannot see the database error in the ShopLite logs.
Round 1 of 2Nested try blocks and which catch runs
The method parses a number in an inner try that catches only NumberFormatException; the outer try catches ArithmeticException. It runs with "5", "abc" and "0".
Example 4 · Nested try: which catch, which finally
public class NestedTryDemo { static void run(String input) { try { System.out.println("outer try"); try { int n = Integer.parseInt(input); System.out.println("10 / n = " + (10 / n)); } catch (NumberFormatException e) { System.out.println("inner catch: not a number"); } finally { System.out.println("inner finally"); } System.out.println("after inner try"); } catch (ArithmeticException e) { System.out.println("outer catch: " + e.getMessage()); } finally { System.out.println("outer finally"); } }
public static void main(String[] args) { run("5"); System.out.println("--"); run("abc"); System.out.println("--"); run("0"); }}outer try 10 / n = 2 inner finally after inner try outer finally -- outer try inner catch: not a number inner finally after inner try outer finally -- outer try inner finally outer catch: / by zero outer finally
What this code does
- "abc" is handled by the inner catch, so the code after the inner try still runs.
- Division by zero has no inner catch: the inner finally runs, then the exception jumps to the outer catch and skips "after inner try".
Java looks for the first matching catch, from the innermost try outwards. If the inner try has no match, its finally runs first, then the exception moves to the outer catches and the code after the inner try is skipped. Within one try, catches are checked top to bottom and only one runs.
Revise: Multiple catch and exception flow (opens in a new tab).
Order of execution
Nested try with the input "0"
Tap the steps in the order Java runs them.
Unreachable catch blocks: compile errors
A multi-catch is one catch (A | B e) block that handles two exception types. A and B must not be parent and child of each other, or the code does not compile.
The program catches FileNotFoundException before its parent IOException, then shows System.exit skipping finally.
Example 5 · Catch order that compiles, and the exit that skips finally
import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;
public class CatchOrderDemo { static String open(String name) { try { new FileReader(name).close(); return "opened"; } catch (FileNotFoundException e) { // subclass first return "FileNotFoundException"; } catch (IOException e) { // then its parent return "IOException"; } }
public static void main(String[] args) { System.out.println(open("no-such-marks-file.txt")); try { System.out.println("in try, calling System.exit(0)"); System.exit(0); } finally { System.out.println("finally (never printed)"); } }}FileNotFoundException in try, calling System.exit(0)
What this code does
- Subclass catches must come before parent catches; swapping the two would fail with "exception FileNotFoundException has already been caught".
System.exitstops the JVM immediately, so the finally block never runs. It is the classic answer to "is finally always executed?"
The compiler rejects catch blocks that can never run. These are the real javac messages for the cases interviewers show:
catch (Exception e)beforecatch (IOException e): "exception IOException has already been caught". Put subclasses first.- A checked exception the try body cannot throw: "exception IOException is never thrown in body of corresponding try statement". This does not apply to
Exception,Throwableor unchecked types. catch (FileNotFoundException | IOException e): "Alternatives in a multi-catch statement cannot be related by subclassing".- A statement after a try whose every path returns or throws: "unreachable statement".
Fix the error
Fix the catch error
Read the error, then pick the line that fixes it.
Round 1 of 2
Two related types in one multi-catch.
Error
OpenFile.java:9: error: Alternatives in a multi-catch statement cannot be related by subclassing Alternative FileNotFoundException is a subclass of alternative IOException
Next step
Check your understanding
12 quick questions