1.3.7 · D3Python Intermediate

Worked examples — Exception hierarchy

3,055 words14 min readBack to topic

You already met the family tree of exceptions: BaseException at the very top, Exception for "normal" errors, and specific leaves like KeyError. This page does one job — it drags every distinct kind of situation into the light and works each one by hand, so you never meet a case in real code that you have not already seen here.


The scenario matrix

Before any code, let us list every class of situation an exception-handling block can face. Each later example is tagged with the exact example number that fills it.

# Case class What is special about it Example
A Exact leaf match handler names the precise exception Ex 1
B Parent catches child handler names an ancestor, child rolls up to it Ex 1, 2
C Sibling divergence two children of one parent, handled together Ex 2
D Order matters (dead code) general-before-specific → later handler unreachable Ex 3
E Degenerate / zero input zero divisor, empty container, None Ex 1, 4
F Limiting value float result past the range ceiling → inf, not an error Ex 4
G BaseException trap Ctrl+C / SystemExit slipping through a too-broad catch Ex 5
H No handler at all ball rolls off the top → crash Ex 6
I Real-world word problem file that may be missing or unreadable Ex 7
J Bare / tuple catch-all except: and except (E1, E2): idioms Ex 8
K Exam twist else/finally + re-raise Ex 9

The rest of the page fills every one of cells A–K.


Cells A, B, E — Arithmetic branch

Figure — Exception hierarchy

Cells B, C — Sibling divergence under LookupError

Figure — Exception hierarchy

Cell D — Order matters (dead code)


Cells E, F — Zero-division vs the float ceiling

Figure — Exception hierarchy

Cell G — The BaseException trap

Figure — Exception hierarchy

Cell H — No handler: the crash case


Cell I — Real-world word problem


Cell J — Bare catch-all and the tuple syntax


Cell K — Exam twist: else, finally, and re-raise


Recall Quick self-test

Handler order rule ::: most-specific first, most-general last, else children become dead code except Exception catches Ctrl+C? ::: No — KeyboardInterrupt is under BaseException, beside Exception Two siblings sharing one handler ::: name their common parent, e.g. LookupError for IndexError + KeyError Catch several unrelated types in one clause ::: except (E1, E2): tuple form Danger of a bare except: ::: it equals except BaseException: and swallows Ctrl+C / sys.exit() When does else run ::: only when the try body raised nothing When does finally run ::: always, even after a return or a re-raise inside except Float division past the range ceiling ::: returns float('inf') silently — no exception; test with math.isinf

Where to go next