为 except 块中的错误分配名称并在以后使用它们

Assigning names to errors in except blocks and using them later

这段代码有效:

try:
    raise Exception('oh no!')
except Exception as e:
    error = e

print(error) # prints "oh no!"

此代码片段失败:

try:
    raise Exception('oh no!')
except Exception as e:
    e = e

print(e) # NameError: name 'e' is not defined

怎么回事?

在Python,

except Exception as e:
    error = e

相当于

except Exception as e:
    try:
        error = e
    finally:
        del e

eexcept块之后被删除。如果您将 e 分配给 e,它将被删除 - 但是,这仅适用于别名。如果将其分配给 errore 也会被删除,但不会删除 error

来源:https://docs.python.org/3/reference/compound_stmts.html#the-try-statement