Python executes the `try` suite first. If an exception occurs, the remaining lines in `try` are skipped and the first matching `except` block runs; `else` is skipped. If `try` finishes with zero exceptions, all `except` blocks are skipped and `else` runs. Regardless of whether an exception was raised, handled, unhandled, or bypassed by `return`, the `finally` block always executes before control leaves the construct.
- 1. How Control Branches Between try, except, and else
- 2. Why finally Always Executes—Even with return or Uncaught Errors
- 3. Tracing Multi-Case Exam Questions Without Shortcuts
- 4. Complete try-except-else-finally Execution Trace
- 5. Execution Paths Across All Four Clauses
- 6. Common Mistakes & Top Scorer Tips
- 7. Interactive Concept Check Quiz
- 8. Frequently Asked Questions
1. How Control Branches Between try, except, and else
Inside a `try` suite, Python runs statements sequentially until either the block completes normally or a runtime exception interrupts execution. The instant an error triggers—say a `ValueError` on line 3 of a five-line `try` block—lines 4 and 5 never run. Python scans the attached `except` clauses top to bottom and enters only the first handler whose exception class matches the raised error (or a parent class like `Exception`). Multiple `except` blocks are mutually exclusive: once one matches, remaining handlers are ignored. The `else` clause runs exclusively when the `try` block finishes cleanly without raising any exception. Placing normal continuation code in `else` rather than inside `try` is a core CBSE best practice because it prevents the `except` handler from accidentally catching unrelated errors raised by follow-up logic that you never intended to guard.
- Syntax order is strictly `try` -> `except` (one or more) -> `else` (optional) -> `finally` (optional).
- Keep `try` blocks narrow; move post-success logic into `else` to avoid masking bugs.
- Always place specific exceptions (`ZeroDivisionError`) before general ones (`Exception`).
2. Why finally Always Executes—Even with return or Uncaught Errors
Unlike post-`try` statements placed after the block, a `finally` suite is guaranteed to run under every possible exit path. If `try` succeeds and `else` finishes, `finally` runs last. If an `except` block handles an error, `finally` still runs afterward. Even when an unhandled exception propagates upward—or when a `return`, `break`, or `continue` statement attempts to exit `try`, `except`, or `else` early—Python suspends that exit, runs `finally`, and then resumes returning or propagating the pending exception. This guarantee makes `finally` indispensable for closing database cursors, releasing network sockets, or flushing log buffers. Note one subtle CBSE exam trap: if `finally` itself contains a `return` statement, that `return` overrides any earlier `return` value or pending exception from `try` or `except`, silently discarding the original result.
- If an unhandled error occurs in `try`, `finally` runs first, then Python prints the traceback.
- A `return` inside `try` still triggers `finally` before handing the value back to the caller.
- Avoid placing `return` inside `finally` because it swallows active exceptions.
3. Tracing Multi-Case Exam Questions Without Shortcuts
Board questions typically give a helper function containing all four clauses and call it three times with valid input, bad input, and an unhandled error type. To trace reliably, mark every call with one of four outcomes: clean success, caught exception, uncaught exception, or early return. When `try` succeeds, draw a line straight through `try` -> `else` -> `finally`, skipping every `except`. When a caught exception occurs, jump from the failing line inside `try` straight to the matching `except` -> `finally`, skipping `else`. Remember that lines written outside and below `finally` only execute if any raised exception was caught (or no error occurred); if an exception goes uncaught, `finally` runs and the remaining outer lines are aborted. Practicing all four combinations on one compact function makes predicting CBSE 3-mark output questions completely mechanical.
- Clean `try`: runs `try` -> `else` -> `finally` -> post-block code.
- Caught error: runs partial `try` -> matching `except` -> `finally` -> post-block code.
- Uncaught error: runs partial `try` -> `finally` -> propagates upward (skips `else` and post-block).
4. Complete try-except-else-finally Execution Trace
def parse_ratio(num_str, den_str):
print("--- Case:", num_str, "/", den_str)
try:
num = int(num_str)
den = int(den_str)
ratio = num / den
print("try computed:", ratio)
except ValueError:
print("except: invalid integer")
except ZeroDivisionError:
print("except: division by zero")
else:
print("else: clean result =", ratio)
return ratio
finally:
print("finally: cleanup done")
print("after try-finally block")
return None
print("Returned:", parse_ratio("20", "4"))
print("Returned:", parse_ratio("20", "0"))
print("Returned:", parse_ratio("abc", "2"))
Verified Console / Dry-Run Output:
--- Case: 20 / 4
try computed: 5.0
else: clean result = 5.0
finally: cleanup done
Returned: 5.0
--- Case: 20 / 0
except: division by zero
finally: cleanup done
after try-finally block
Returned: None
--- Case: abc / 2
except: invalid integer
finally: cleanup done
after try-finally block
Returned: None
5. Execution Paths Across All Four Clauses
| Scenario in try | except Runs? | else Runs? | finally Runs? | Post-Block Runs? |
|---|---|---|---|---|
| No exception raised | No | Yes | Yes | Yes (unless else returns) |
| Matching exception raised | Yes (first match) | No | Yes | Yes (unless except returns) |
| Unmatched exception raised | No | No | Yes | No (propagates upward) |
| return executed inside try | No | No | Yes (before returning) | No |
Crack Exception Tracing Questions Effortlessly
Practice CBSE Class 12 CS 083 try-except-else-finally and file-handling error drills at 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods). Book a free 1:1 trial class.
6. Common Mistakes & Top Scorer Tips
- Avoid Mistake: Putting `else` before `except` or after `finally`, which raises a `SyntaxError`.
- Avoid Mistake: Expecting `else` to execute after a caught exception is handled by `except`.
- Avoid Mistake: Assuming `finally` is skipped when `try` or `else` executes a `return` statement.
- Examiner / Mentor Tip: Note that an `else` clause requires at least one `except` clause before it; `try...else...finally` without `except` is invalid syntax.
- Examiner / Mentor Tip: If a `try` block raises an unhandled error, `finally` still prints before the traceback.
- Examiner / Mentor Tip: Mention resource cleanup (files, DB connections) when asked why `finally` exists in 2-mark theory questions.
7. Interactive Concept Check Quiz
Question: Consider: def test(): try: return 10; finally: return 30. What does print(test()) output?
8. Frequently Asked Questions
Can we write a try block with finally and no except block?
Why not put the else code at the bottom of the try block instead?
What happens if an exception is raised inside the except block itself?
Explore Related Lessons & Free Interactive Tools
- All 110 Guides in CBSE CS (083) & IP (065) Hub
- Using raise, assert, ZeroDivisionError, and Custom Exceptions in Python
- Python random Module Probable Output Questions: randint vs randrange (CBSE 083)
- Python String Slicing s[::-1] and Negative Index Outputs
- Interactive Tool: CBSE CS 083 Python Output Predictor Quiz
- Interactive Tool: CBSE SQL GROUP BY / HAVING / JOIN Query Evaluator
