1.3.6 · D3Python Intermediate

Worked examples — Raising exceptions — raise, custom exception classes

2,719 words12 min readBack to topic

We treat "cases" the way a geometry deep-dive treats quadrants: each cell of the matrix below is a distinct region of behaviour, and we make sure a worked example lands in every cell.


The scenario matrix

Think of "what you write after raise" and "what state you're in" as two axes. Every combination lands somewhere:

Cell Case class What triggers it Danger if you get it wrong
A raise Class (bare class) You give the type, no message Empty .args — nothing prints
B raise Class("msg") (instance) You give type + message This is the normal, safe path
C Custom exception, pass body Named category, no data Handler knows what, not how much
D Custom exception carrying data Handler needs the numbers Forgetting super().__init__ → blank message
E Bare raise (re-raise) Inside except, pass it on Losing the original traceback
F raise B from A (chaining) Translate low-level → domain Hiding the real cause
G Degenerate / zero numeric input amount = 0 or negative Continuing with corrupt state
H1 The guard check Refuse invalid input up front Corrupt state slips through
H2 The "make ≠ raise" trap return Exception(...) Caller gets an object, not a crash
I Real-world word problem Bank withdrawal Silent wrong balance
J Exam twist Which except catches it? Wrong handler runs / none runs

The 8 examples below cover all eleven cells (some examples hit two).


Example 1 — Cells A & B: class vs instance


Example 2 — Cell C: custom exception, pass body


Example 3 — Cell D: custom exception carrying data


Example 4 — Cell D danger: forgetting super().__init__


Example 5 — Cell E: bare raise re-raises


Example 6 — Cell F: raise B from A chaining


Example 7 — Cells G, H1, I: real-world withdrawal with degenerate inputs

Figure — Raising exceptions — raise, custom exception classes

Example 8 — Cell H2: the "make ≠ raise" trap


Example 9 — Cell J: exam twist, which except catches it?


Coverage check

Recall Did we hit every cell A–J?

A,B → Ex 1 · C → Ex 2 · D → Ex 3 & 4 · E → Ex 5 · F → Ex 6 · G,H1,I → Ex 7 · H2 → Ex 8 · J → Ex 9. Every cell of the matrix has a worked example.

Recall Zero and negative both funnel where in the withdrawal example?

To the same ValueError guard amount <= 0 (cell H1) — one narrow check catches both degenerate cases.

Recall Why did Example 9 print

"exception" and not "funds"? except clauses match first-to-last by isinstance; the broad except Exception sits above the specific one and shadows it.


Connections