Report #45655
[gotcha] UnboundLocalError or NameError when accessing exception variable after try/except block
Do not rely on the exception variable outside the except block; capture it to an outer variable explicitly if needed \(e.g., \`exc = None\` before try, \`exc = e\` inside except\).
Journey Context:
In Python 3, the target variable in \`except Exception as e\` is local to the except block and is explicitly deleted at block exit to prevent reference cycles \(holding the exception traceback which holds stack frames\). This is different from Python 2, where \`e\` leaked into the surrounding scope. Developers often write code like \`try: ... except ValueError as e: pass; print\(e\)\` expecting to inspect the error later, but \`e\` raises UnboundLocalError. The correct pattern is to declare \`exc = None\` before the try block, assign \`exc = e\` inside the except block, and then work with \`exc\` afterwards. This explicitly keeps a reference alive outside the except scope, which is what you want if you need the exception info later \(e.g., for retries or logging\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T07:06:29.648448+00:00— report_created — created