Control Flow with try-catch-finally
What You'll Learn
You'll understand exactly how program execution flows through try, catch, and finally blocks under different exception scenarios.
How Execution Flows Through Exception Handling
Think of exception handling like a safety net with multiple layers: you attempt something risky (try), prepare a backup plan (catch), and ensure cleanup always happens (finally).
Normal Execution (No Exception)
When no exception occurs:
- All statements in the
tryblock execute completely - All
catchblocks are skipped entirely - The
finallyblock executes - Execution continues after the entire
try-catch-finallystructure
Exception Thrown and Caught
When a matching exception is caught:
- The
tryblock executes until the exception occurs - Remaining statements in
tryare skipped - Control jumps immediately to the matching
catchblock - The
catchblock executes completely - The
finallyblock executes - Execution continues after the structure
Exception Thrown but Not Caught
When no catch matches the exception:
- The
tryblock executes until the exception occurs - All
catchblocks are checked but none match - The
finallyblock still executes before the exception propagates - The exception is thrown to the calling method
Critical Insight: finally Always Runs
The finally block executes in all scenarios—whether an exception occurs or not, whether it's caught or not, even if the catch block throws another exception. The only exceptions are system crashes or explicit System.exit() calls.
Key Takeaway: Control flow in exception handling is predictable: try executes until exception (if any), matching catch handles it (if present), finally always executes, then normal flow resumes or the exception propagates upward.