Inspect Exception Handling Metadata
Core idea
CPython 3.13 uses exception table metadata to describe protected instruction ranges and handler targets. Unlike older bytecode layouts, the normal path need not execute a setup instruction for each try block. dis.Bytecode exposes exception_entries in this runtime, an implementation detail. Python-level try, except and finally behavior remains the contract.
import disdef plain(n): return 10 // ndef guarded(n): try: return 10 // n except ZeroDivisionError: return 0print(len(dis.Bytecode(plain).exception_entries) == 0)print(len(dis.Bytecode(guarded).exception_entries) > 0)print(guarded(2), guarded(0))The guarded function contains handler entries; the normal and exception paths return distinct results.
Expected output:
TrueTrue5 0Inspect handler range properties
import disdef read(n): try: return int(n) finally: passentries = dis.Bytecode(read).exception_entriesprint(bool(entries))print(all(e.start < e.end and e.depth >= 0 for e in entries))try: read('bad')except ValueError: print('propagated')Entries identify protected ranges and stack unwind depth. finally alone does not swallow ValueError.
Expected output:
TrueTruepropagatedCommon mistake
Do not decode or edit co_exceptiontable bytes as a stable public format. “Zero-cost” exception handling does not mean raising or handling an exception is free.
Practice
Compare dis.Bytecode(...).exception_entries for try/except and try/finally functions on your pinned CPython runtime; explain which exceptions propagate.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exception machinery
Check your understanding of exception machinery.
What is printed?
import disdef f(): return 1print(bool(dis.Bytecode(f).exception_entries))What is printed?
def f(): try: return 2 finally: print('cleanup')print(f())What does exception table metadata describe?
Does finally automatically suppress an exception?