Python Exception Handling Explained: try, except, finally, Raising Errors and Worked Traces
Learn one reliable model for Python exceptions through a four-record score parser, handler matching, propagation, cleanup, and solved output traces.
KnowledgeGate Team
Exam prep & CS education

Your program accepts "72", then stops when the next input is "x"; or you know try and except but cannot predict whether else and finally will run. Use Exceptions in Python: Handle Errors with try, except and finally for safe everyday handling patterns. The four-record score parser below goes further into exact output, subclass matching, cleanup, propagation, and exception translation. The broader Coding & DSA Courses for Placements page is a useful learning route alongside it.
Python exceptions: what is raised and what is matched
An exception is an object that signals normal execution cannot continue at a particular point. Python raises that object, searches for a compatible handler, and unwinds outward through calling functions when the current block cannot handle it. The official Python 3 Errors and Exceptions tutorial documents this language behaviour.
Different failures have different classes:
10 / 0raisesZeroDivisionError.int("x")raisesValueError.{"id": 7}["score"]raisesKeyError.
The class identifies the failure, while the object can carry a message or related values. An unwanted result is not automatically an exception.
The matching hierarchy is BaseException, Exception, ValueError, then its child ScoreOutOfRangeError. Python selects the first compatible except from top to bottom, so the child handler must precede its parent.
The execution order of try, except, else and finally
Put risky statements in try and handle a specific failure in except. Success work belongs in else, which requires a clean try. Cleanup belongs in finally, which runs as control leaves under ordinary Python execution.
The three possible paths are:
Case | Path |
|---|---|
| Parsing returns |
|
|
|
|
Keeping success work in else prevents an append or later calculation from being mistaken for a parsing failure. The order is except or else, then finally. except and else never both run in one pass.

Worked example: validate four scores without losing the valid records
Use the following parser and loop:
class ScoreOutOfRangeError(ValueError):
pass
def parse_score(raw):
score = int(raw)
if not 0 <= score <= 100:
raise ScoreOutOfRangeError(f"{score} outside 0..100")
return score
records = [("Asha", "72"), ("Kabir", "x"), ("Meera", "95"), ("Ravi", "-4")]
accepted = []
for name, raw in records:
try:
score = parse_score(raw)
except ScoreOutOfRangeError as exc:
print(f"{name}: range error ({exc})")
except ValueError:
print(f"{name}: not an integer")
else:
accepted.append(score)
print(f"{name}: accepted {score}")
finally:
print(f"{name}: checked")
print(accepted)
print(sum(accepted) / len(accepted))The exact output is:
Asha: accepted 72
Asha: checked
Kabir: not an integer
Kabir: checked
Meera: accepted 95
Meera: checked
Ravi: range error (-4 outside 0..100)
Ravi: checked
[72, 95]
83.5Asha and Meera parse and reach else. Kabir never produces an integer. Ravi produces -4 but fails the range check. Only Asha and Meera are appended, so (72 + 95) / 2 = 167 / 2 = 83.5.

Raising, propagating and translating exceptions
raise ScoreOutOfRangeError(...) deliberately creates a domain-specific failure. A bare raise inside a handler re-raises the current exception. raise NewError(...) from exc translates a low-level failure while preserving its causal link.
Now trace an unhandled exception through two functions:
def divide(total, count):
return total / count
def report():
try:
return divide(167, 0)
finally:
print("report cleanup")
try:
print(report())
except ZeroDivisionError:
print("cannot average zero scores")The exact output is report cleanup, then cannot average zero scores. No number is printed because 167 / 0 never returns. The finally suite runs while control leaves report, then the unmatched exception reaches the outer handler.
Catch at the nearest layer that can recover or add useful context. A parser could use raise ScoreImportError("Kabir has invalid score") from exc. Do not swallow the failure and return a misleading 0. Logging and re-raising may be appropriate, but silently continuing changes behaviour.
Exception-handling traps and the direct fixes
Putting the broad handler first
If except ValueError comes first, Ravi's custom subclass matches it and the range-specific handler is missed. Put ScoreOutOfRangeError first.
Returning from finally
def choose():
try:
return 7
finally:
return 9print(choose()) outputs 9 because the return in finally replaces the pending 7. Treat this as a warning. Use finally for cleanup, not ordinary result selection.
Catching too much
A bare except: can hide control-flow exceptions. Catch ValueError for int(raw), the relevant file exception for file lookup, and ScoreOutOfRangeError for the range rule. Do not leave a production handler containing only pass.
Continuing with stale state
A stale score from an earlier pass could be appended for the wrong learner. Keep the append in else, where only a successful current record reaches it.
How exams and output questions test exception flow
Typical tasks ask you to identify the raised class, choose the first handler, place else and finally in output order, trace propagation, distinguish forms of raise, or spot a return in finally. These are representative forms, not a fixed exam pattern.
Try this 20-second trace:
try:
print(10 // 0)
except ZeroDivisionError:
print("Z")
else:
print("E")
finally:
print("F")Label the path before running it. 10 // 0 raises ZeroDivisionError, so the exact output is Z and then F. E is skipped, and no quotient is printed.
Output tracing becomes easier when every state change is written down. Python Output-Based Questions applies that method to lists, slicing, and mutability; exception routing adds the question of which suite runs next. Exam authorities define marks, weightage, dates, and paper structure in their current notifications; Python exception rules do not change with a particular exam.
Python exception handling: the short version and next step
Risky code goes in
try.The first compatible
exceptruns.elseruns only after a cleantry.finallyperforms cleanup as control leaves.raisedeliberately signals a failure.An unhandled exception propagates outward.
The worked invariant is worth retaining: accepted scores are [72, 95], and their mean is 83.5.
For a five-minute exercise, reuse the parser with [("Nia", "40"), ("Om", "101"), ("Pia", "60")]. Predict all six per-record lines before execution. Nia prints Nia: accepted 40, then Nia: checked. Om raises ScoreOutOfRangeError("101 outside 0..100"), so the loop prints Om: range error (101 outside 0..100), then Om: checked. Pia prints Pia: accepted 60, then Pia: checked. The final list is [40, 60], and the mean is (40 + 60) / 2 = 100 / 2 = 50.0.
Next, wrap validation around your own small functions. For a sequenced language path, use Python Course - Concepts, MCQs & Coding. When you are ready to combine Python control flow with structured problem solving, continue to DSA Using Python.
Keep learning
Exceptions in Python: Handle Errors with try, except and finally
Learn how Python exceptions change control flow, how to catch expected failures without hiding bugs, and when to use else, finally, raise, and custom exceptions.
Exception Handling in Java: Checked vs Unchecked, finally Traps and Output Questions
Replace guesswork with precise Java exception rules. Trace two classic finally outputs, order catches correctly, and preserve causes when wrapping failures.
Exception Handling in C++: try, catch, throw and two runnable examples
Follow two runnable programs to see how C++ exceptions change control flow, select handlers and destroy local objects during stack unwinding.
C++ Exception Handling: Typed Errors, Stack Unwinding and Safe Recovery
Build a small C++ parser that reports machine-readable failures, recovers only from a malformed optional field, and preserves saved state when a required field fails.





