Log inStart free
LESSON 1.07 · 6 STAGES · 3 CONTROLS · 3 CHECKSPRO · PREVIEW

Exceptions and context managers

Watch an exception travel down the call stack, and see which code still runs.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 3 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 1.07 · EXCEPTION BAY4 FRAMES · TRACEBACK 1 · EXCEPTION IN SCALE
01
Stage 1 of 6 · Raise
raise makes a ValueError exception object. It holds its args and a traceback.
Explain it simply

You see the call stack on the left, with the newest call on top. main called work, and work called scale with n set to -1. So the raise line runs. It makes an exception: an object that reports the error, in red on the right.

The stack holds 4 frames: the module, main, work and scale. scale raised a ValueError. Its args hold the message n < 0. Its traceback has 1 entry: scale, line 24.

frame and nameobjectid and referenceexception, traceback, bad valueresult and output
call stack · newest on topheap<module>27main()main()11try:12 print(work())13except ValueError as e:14 print("caught:", e)15finally:16 print("finally")work()19with Guard() as g:20 return scale(-1)scale(-1)23if n < 0:24 raise ValueError("n < 0")25return n * 2gnGuard objectint -1ValueErrorobject · id 3008args('n < 0',)__traceback__ · oldest firstscale line 24 raise ValueError("n < 0")$ python demo.py← printed by __enter__entercall stack · newest on topheap<module>27main()main()11try:12 print(work())13except ValueError as e:14 print("caught:", e)15finally:16 print("finally")work()19with Guard() as g:20 return scale(-1)scale(-1)23if n < 0:24 raise ValueError("n < 0")25return n * 2gnGuard objectint -1ValueErrorobject · id 3008args('n < 0',)__traceback__ · oldest firstscale line 24 raise ValueError("n < 0")$ python demo.py← printed by __enter__enter
Toy: 4 frames · CPython 3.12 rules · ids are stand-ins · frames a traceback keeps are not drawn
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
e=(type, args, traceback)\sy{exc}{grad}{e} = (\sy{type}{grad}{\mathrm{type}},\ \sy{args}{ink}{\mathrm{args}},\ \sy{tb}{grad}{\mathrm{traceback}})
e=(ValueError, (’n < 0’,), [scale:24])e = (\texttt{ValueError},\ \texttt{('n < 0',)},\ [\texttt{scale:24}])

An exception object holds its class, its args and its traceback.

Common mix-ups

MYTHAn exception inside a with block skips __exit__.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01After the assert fails, does any code run before the traceback prints?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 3 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.