1.3.5 · D3Python Intermediate

Worked examples — Exception handling — try, except (specific), else, finally

4,174 words19 min readBack to topic

This page is the stress test for the parent topic. The parent showed you the four blocks. Here we walk through every kind of situation the machine can land in — not just "an error happened", but which error, whether it was caught, what ran after, and the weird corner cases where two rules fight each other.

Before any code: remember the one picture. There are four roomstry, except, else, finally — and Python's control (think of it as a glowing marble) rolls through some of them depending on what happens. Our whole job here is to trace the marble in every possible track.

Figure 1 — the four rooms and the marble's tracks.

Figure — Exception handling — try, except (specific), else, finally

Figure 3 — an exception is a labelled box (type + message), and each except runs isinstance on it.

Figure — Exception handling — try, except (specific), else, finally


The scenario matrix

Every exception-handling situation is one of these cells. The worked examples below are each tagged with the cell(s) they cover, so by the end every row is filled.

Cell Situation Marble path Covered by
A try succeeds, nothing raised try → else → finally Ex 1
B try raises, a specific except matches try(partial) → except → finally Ex 2
C try raises, a parent class except catches a child try(partial) → except → finally Ex 3
D Two except clauses, order decides the winner first matching wins Ex 3
E try raises, no except matches → propagates try(partial) → finally → outward Ex 4
F finally runs even when try does return return "pauses", finally runs, then return completes Ex 5
G Degenerate / zero-ish input (empty string, division by zero) depends on which error fires Ex 6
H Real-world word problem (parse a config line safely) success + failure branch together Ex 7
I Exam twist: finally overrides a return value finally's return wins Ex 8
J Bare except: swallows something it shouldn't (limiting/danger case) catches even Ctrl-C Ex 9
K An exception is raised inside except or else not re-caught by the same construct Ex 10
L finally itself raises its exception replaces whatever was pending Ex 11

We will now visit all twelve cells (A–L), each with its own fully worked trace.













Recall Every cell, one line each

Cell A — try succeeds ::: path is try → else → finally, and except is skipped (Rule 4). Cell B — specific except matches ::: try(partial) → except → finally, else skipped (Rules 1, 2, 4, 5). Cell C — parent catches child ::: except LookupError catches KeyError via isinstance (Rule 2). Cell D — order decides ::: first matching clause wins and scanning stops, so child before parent (Rule 2). Cell E — no match ::: finally runs, then the exception propagates outward (Rules 3, 5). Cell F — finally through return ::: return is set aside, finally runs, then return completes (Rule 5). Cell G — degenerate input ::: empty string → ValueError; divide by zero → ZeroDivisionError. Cell H — real-world config parse ::: success → else returns n; no "=" or bad int → except returns None; finally always prints. Cell I — return in finally ::: it overrides the pending value/exception (never do this). Cell J — bare except ::: swallows even KeyboardInterrupt; use except Exception instead. Cell K — error inside except/else ::: not re-caught by the same construct; it propagates outward (Rule 3). Cell L — finally itself raises ::: the finally's exception replaces the pending one; the original is displaced.


Connections

  • The exception class hierarchy — BaseException, Exception, LookupError — why KeyError is a LookupError and why KeyboardInterrupt is not an Exception.
  • Raising exceptions — raise and custom exception classes — Ex 9, 10 and 11 use raise to build the corner cases.
  • Context managers — with statement and __enter__/__exit__ — the clean replacement for try/finally, and safer when cleanup can fail (Cell L).
  • File handling in Python — Ex 7's real-world flavour.
  • Debugging and tracebacks — what Cells E, K and L's propagation eventually prints.
  • Logging vs printing errors — what to do with the caught e.

Cell map

success

error

usually

try block runs

finished, no error

raised part-way

a listed except matches

no except matches

else runs

except handles it

propagate outward

finally always runs

finally itself raises