try — Expert Examples
Starts a block of code that will be monitored for exceptions
Exception handling bytecode
How try/except compiles to bytecode.
python
import dis def example(): try: x = 1 / 0 except ZeroDivisionError: return "caught" else: return "ok" finally: pass # cleanup dis.dis(example) # Key bytecodes: # SETUP_FINALLY - sets up the exception handler # POP_EXCEPT - clears the exception state # The finally block is duplicated in both paths
CPython uses SETUP_FINALLY to register exception handlers on an internal block stack. The finally block is compiled into both the normal and exception paths.
Want to try these examples interactively?
Open Expert Playground