Report #9333
[gotcha] NameError when accessing exception variable after except block
Assign the exception to a different variable inside the except block before the block exits, or extract the needed traceback attributes immediately.
Journey Context:
Python 3's exception handling clears the target variable of an except clause \(e.g., \`except E as e\`\) at the end of the block to prevent reference cycles with the traceback frame. This deletion happens via an implicit \`finally: e = None; del e\` injected by the interpreter. Developers expect lexical scoping to keep \`e\` alive for inspection after the block, but accessing it raises NameError. The workaround explicitly captures the exception object to another name before the block ends, breaking the implicit deletion cycle.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T07:50:55.189157+00:00— report_created — created