Catch Variable Reassigned
ID |
python.catch_variable_reassigned |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Python |
Tags |
exception-handling, reliability |
Description
Reports an assignment that reassigns the bound exception variable inside an except … as e: block. Reassigning the catch variable obscures the original exception. Python additionally deletes the bound variable when the except block exits, so the new value vanishes anyway when control leaves the block.
try:
work()
except ValueError as e:
e = wrap(e) # FLAW
log(e)
try:
work()
except ValueError as e:
wrapped = wrap(e) # OK — different name
log(e)
Rationale
The exception variable in except … as e: is intentionally short-lived: Python clears it on block exit to avoid keeping a traceback alive in the surrounding scope. Rebinding e defeats the only purpose of having the alias and silently drops the original exception object.
Remediation
-
Pick a different local name for any wrapping/derivation of the exception.
-
Re-raise (
raise) or store on an outer variable if you need the wrapped exception after the block.