Python Exception Propagation, finally, raise, and Assertions
Introduction
Python exception propagation passes an unhandled error to an enclosing handler while running the cleanup on the way out. A finally block can close a file before the caller receives the error. A raise can pass the same error onward or translate it into a more useful one.
This lesson continues objective 2.1 of PCAP-31-03, in Exceptions (14% of the score, 5 of 40 items). You will trace nested statements, distinguish exception chaining from re-raising, and use assertions for internal assumptions.
Learning objectives
After this lesson you can:
- Describe how an unhandled exception travels through callers and terminates the current execution if nothing handles it.
- Trace the output of nested
trystatements across several functions. - Use
raisewith an exception class, with an instance, and bare inside a handler to re-raise. - Explain exception chaining with
raise ... fromand the effect offrom None. - Predict the interaction between
finallyandreturn. - Use
assertcorrectly and explain whatAssertionErrorcarries.
Propagation along the call stack
When a statement raises an exception, Python looks for a matching handler in the current function. If it finds none, Python unwinds the call, running applicable finally clauses and context-manager cleanup before the exception reaches the caller. This repeats up the chain of callers. If the exception reaches the top of the program without a handler, Python prints a traceback and stops.
def level3():
print("level3 start")
return 1 / 0
print("level3 end") # never runs
def level2():
print("level2 start")
level3()
print("level2 end") # never runs
def level1():
try:
level2()
except ZeroDivisionError:
print("handled in level1")
print("level1 end")
level1()The output is:
level2 start
level3 start
handled in level1
level1 endNotice what does not appear: the end lines of level3 and level2. Each function is cut short at the line where the exception passes through. Execution resumes only after the try statement that handled it, which is inside level1.
Trace the enclosing statements from the raising point outward. Ordinary statements after the failure are skipped, while cleanup runs as control leaves each protected statement. Review the Python exception hierarchy to check which handler matches.
Worked example: where does the handler sit?
Problem. What does the program print?
def convert(text):
try:
return int(text)
except TypeError:
print("type")
return -1
def total(items):
s = 0
for item in items:
try:
s += convert(item)
except ValueError:
print("value")
return s
print(total(["4", "x", None, "6"]))Step 1: item "4". convert("4") returns 4, so s becomes 4.
Step 2: item "x". int("x") raises ValueError. The handler in convert only catches TypeError, so convert is abandoned and the exception reaches total, which has except ValueError. It prints value and the loop continues. s is still 4.
Step 3: item None. int(None) raises TypeError. The handler in convert matches, prints type and returns -1, so s becomes 3.
Step 4: item "6". s becomes 9.
Solution. The output is value, type, then 9.
Why other answers are wrong. The result 10 comes from skipping the "x" item and ignoring the -1 that convert(None) returns. A program that prints type before value has the order of the list wrong.
Raising exceptions with raise
The raise statement creates an exception and starts propagation from that line.
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > balance:
raise RuntimeError("insufficient funds")
return balance - amountYou can raise an exception instance or an exception class that can be constructed without arguments. For raise ValueError, Python creates a ValueError with args == (). A custom class with a required constructor argument would fail to instantiate.
Re-raising with a bare raise
A bare raise re-raises the active exception. It preserves the exception object and its traceback unless code has explicitly modified that traceback. This is how you log an error and still let callers deal with it.
def load(path):
try:
with open(path, encoding="utf-8") as stream:
return stream.read()
except OSError:
print("cannot read", path)
raise # the same OSError continues upwardA bare raise outside any handler raises RuntimeError: No active exception to re-raise.
Chaining with raise ... from
Sometimes you want to translate a low-level error into a more meaningful one without losing the original cause.
def parse_age(text):
try:
return int(text)
except ValueError as err:
raise TypeError("age must be numeric") from errThe new exception stores the original in its __cause__ attribute, and the traceback shows both. If you raise a new exception inside a handler without from, Python still links the old one in __context__ and prints "During handling of the above exception, another exception occurred". Writing from None suppresses the displayed context.
| Form | Meaning | Attribute set |
|---|---|---|
raise (inside handler) |
re-raise the active exception | none new |
raise NewError("x") inside handler |
new exception, old one implicitly attached | __context__ |
raise NewError("x") from err |
explicit cause | __cause__ |
raise NewError("x") from None |
hide the previous exception in the traceback | __suppress_context__ is true |
Cleanup with finally
When Python leaves a try statement, finally runs after success or a handler, and while an exception, return, break, or continue is pending. It is meant for cleanup that must happen no matter what, such as closing a file or releasing a lock.
def read_first_line(path):
f = open(path)
try:
return f.readline()
finally:
f.close() # runs before the function really returnsIf the exception is not handled, finally runs first and the exception continues afterward.
def job():
try:
print("working")
raise KeyError("k")
finally:
print("cleanup")
try:
job()
except KeyError:
print("caught")The output is working, cleanup, caught. The cleanup of the inner function happens before the outer handler runs, because the stack unwinds from the inside out.
finally and return
This is a favourite exam trap. If try executes return, the return value is computed first, then finally runs, and then the function returns. If finally itself contains a return, that value replaces the earlier one, and any pending exception is discarded.
def f():
try:
return "try"
finally:
print("finally")
def g():
try:
return "try"
finally:
return "finally"
def h():
try:
raise ValueError("lost")
finally:
return "silent"
print(f()) # prints "finally", then "try"
print(g()) # "finally"
print(h()) # "silent" (the ValueError disappears)A return that leaves finally can suppress an error. CPython 3.14 also emits a SyntaxWarning for return, break, or continue that exits a finally block. In the preceding example, the comments describe normal printed output separately from that warning.
The full order of execution
For a try statement with all four parts, the order is:
- The
tryblock runs until it ends, raises, or returns. - If it raised and a clause matches, that
exceptblock runs. - If it ended normally (no exception, no
return), theelseblock runs. - The
finallyblock runs. - If an exception is still pending, it continues upward; otherwise execution continues after the statement.
Worked example: tracing four paths
Problem. Trace the printed markers and return value for each mode.
def run(mode):
try:
print("A")
if mode == "err":
raise ValueError
if mode == "ret":
return "from try"
except ValueError:
print("B")
return "from except"
else:
print("E")
return "from else"
finally:
print("C")Step 1: run("ok"). A is printed, no exception, no return. The else block prints E and prepares the value "from else". Then finally prints C. Printed: A E C; returned: "from else".
Step 2: run("err"). A, then ValueError. The handler prints B and prepares "from except". finally prints C. Printed: A B C; returned "from except".
Step 3: run("ret"). A, then return "from try" is prepared. Because the block did not end normally, else is skipped. finally prints C. Printed: A C; returned "from try".
Step 4: run("boom"). Mode "boom" matches nothing, so this behaves like "ok".
Why other answers are wrong. Believing else runs after a return in try is the classic mistake. Believing that finally runs only on errors is the other.
Assertions
An assertion states a condition that the programmer believes must be true. If the condition is false, assert raises AssertionError.
def average(values):
assert len(values) > 0, "values must not be empty"
return sum(values) / len(values)
average([]) # AssertionError: values must not be emptyThe syntax is assert condition or assert condition, message. The message becomes the exception's argument, so err.args == ("values must not be empty",). Without a message, args is ().
Important facts:
AssertionErroris a subclass ofException, soexcept Exceptioncatches it.- When Python is started with the
-Ooption, assertions are removed. They must never be used to validate user input or to enforce security. Use them for internal sanity checks and for debugging. assert (condition, "message")with parentheses around both parts creates a non-empty tuple, which is always true, so the check never fails. Recent Python versions warn about it.
| Need | Right tool |
|---|---|
| Reject invalid user input | raise ValueError(...) |
| Report a missing resource | raise FileNotFoundError or let it propagate |
| Check an internal invariant | assert |
| Pass an error to the caller after logging | bare raise |
| Replace a low-level error with a domain one | raise ... from err |
Exceptions raised inside handlers and inside finally
A handler is ordinary code, so it can fail too. When an exception is raised inside an except block, it is not caught by the sibling except clauses of the same try statement. Those clauses only protect the try block. The new exception propagates outward, and the finally clause of the same statement still runs.
def convert(value):
try:
return int(value)
except ValueError:
print("handler")
return 1 / 0 # new error inside the handler
except ZeroDivisionError:
print("never reached")
finally:
print("finally")
try:
convert("x")
except ZeroDivisionError:
print("outer")The output is handler, finally, outer. The second clause except ZeroDivisionError does not protect the first handler; the finally block runs while the new exception is pending; the outer try statement catches it. The original ValueError is kept in the __context__ attribute of the ZeroDivisionError.
If finally raises a new exception while another is pending, the new one propagates and the earlier one normally becomes its context. An explicit cause or from None changes how the chain is displayed. This is why cleanup code should be short and defensive.
Worked example: the nested statement
Problem. What is printed?
def inner():
try:
raise KeyError("a")
except KeyError:
print(1)
raise ValueError("b")
finally:
print(2)
def outer():
try:
inner()
except KeyError:
print(3)
except ValueError as err:
print(4, err.args, type(err.__context__).__name__)
finally:
print(5)
outer()Step 1. inner raises KeyError; its handler prints 1 and raises ValueError.
Step 2. Before the ValueError leaves inner, the finally block prints 2.
Step 3. In outer, the ValueError is tested against except KeyError (no match) and except ValueError (match). It prints 4 ('b',) KeyError, because the implicitly chained context is the original KeyError.
Step 4. The finally block of outer prints 5.
Solution. The lines are 1, 2, 4 ('b',) KeyError, 5.
Why the other answers are wrong. Printing 3 assumes the KeyError escapes from inner, but it was replaced by the ValueError. Printing 2 after 4 forgets that the innermost finally always runs first, as the stack unwinds from the inside out.
Common patterns
Cleanup plus recovery. Use finally for cleanup and except for recovery, and keep them separate.
def safe_read(path):
f = None
try:
f = open(path)
return f.read()
except FileNotFoundError:
return ""
finally:
if f is not None:
f.close()The check f is not None matters: if open fails, f is still None, and calling close() on it would raise a new AttributeError that hides the real problem. The with open(path) as f: statement does this automatically and is usually preferable.
Retry loop. Combine try inside a loop with continue and else:
for attempt in range(3):
try:
value = int(input("number: "))
except ValueError:
print("try again")
else:
breakCommon pitfalls and exam tips
- Skip ordinary statements after the failure while unwinding. Run applicable cleanup before entering the outer handler.
finallyalways runs, even afterreturn,breakandcontinue; areturninsidefinallywins.elseis skipped if thetryblock returns or raises.- A bare
raiseneeds an active exception; outside a handler it fails withRuntimeError. - Chaining:
from errsets__cause__;from Nonehides the context. assertcan be disabled with-O; it is not a validation mechanism.- Inspect errors raised by handlers and cleanup. A new exception propagates outward and normally retains the prior exception as context.
Exam tip. Number the output lines as you trace. Write
A,B,Cin order and cross out the lines that are skipped by an exception. Handle nestedtrystatements from the innermost outward, and always runfinallybefore moving to the outer handler.
Mini case study: the export that kept the file locked
A reporting script writes a CSV file and then sends it.
def export(rows, path):
out = open(path, "w")
try:
for row in rows:
out.write(",".join(row) + "\n")
out.close()
except OSError:
print("export failed")On a test run, one row contains the integer 5 instead of text. The script crashes with a traceback, and a second export in the same long-running process can encounter an open file handle.
Task. Explain the problem and fix it.
Solution.
",".join(row)raisesTypeErrorfor a non-string item. The handler only catchesOSError, so the exception propagates.out.close()is inside thetryblock after the loop, so it is skipped when the exception passes through. Relying on later object cleanup makes resource release timing dependent on the runtime and remaining references. Process termination closes its handles, but the service may keep running.- Cleanup must be unconditional, so it belongs in
finally(or in awithblock). Convert items withstr()if the data may contain numbers.
def export(rows, path):
out = open(path, "w")
try:
for row in rows:
out.write(",".join(str(x) for x in row) + "\n")
except OSError as err:
print("export failed:", err)
raise
finally:
out.close()Once the file is open, finally closes it when the protected code exits. See file streams and resource cleanup for a context-manager pattern. The simplified text format here assumes fields contain no commas, quotes, or newlines. Use a CSV writer when those characters are allowed. The handler reports the failure and re-raises, so the caller still knows the export did not complete.
Key terms
- Propagation: passing an unhandled exception to the caller, level by level.
- Traceback: the report printed when an exception reaches the top.
raise: statement that creates or re-raises an exception.- Chaining: linking a new exception to the one that caused it (
__cause__,__context__). finally: cleanup clause used during normal Python unwinding.assert: statement that raisesAssertionErrorwhen a condition is false.-Ooption: interpreter flag that removes assertions.
Summary checklist
- I can follow an exception through nested calls and list the skipped lines.
- I know that the handler nearest to the raising line is tried first, then outer ones.
- I can use
raisewith a class, an instance, bare, and withfrom. - I can trace
try/except/else/finallyincludingreturn. - I know a
returninfinallyoverrides everything. - I use
assertfor invariants only and know-Odisables it. - I place cleanup in
finallyor in awithblock.
Official sources
- Python Institute, PCAP-31-03 syllabus: https://pythoninstitute.org/pcap-31-03-exam-syllabus (opens in a new tab)
- Python tutorial, Raising and handling exceptions, clean-up actions: https://docs.python.org/3.14/tutorial/errors.html (opens in a new tab)
- Language reference, the
raise,tryandassertstatements: https://docs.python.org/3.14/reference/simple_stmts.html (opens in a new tab)
