由于在 Python 中变量可以在它们的循环和 try
-except
block 之外访问,我天真地认为下面的代码片段可以正常工作,因为 e
将可访问:
try:
int('s')
except ValueError as e:
pass
print(e)
在 Python 2(2.7 测试)中,它确实按我预期的那样工作,输出是:
invalid literal for int() with base 10: 's'
然而,在 Python 3 中,令我惊讶的是输出是:
NameError: name 'e' is not defined
这是为什么?
后来我找到了一个答案 PEP 3110解释在 Python 3 中,捕获的名称在 except
套件的末尾被删除,以实现更有效的垃圾收集。如果您希望避免这种情况的发生,还有推荐的语法:
Situations where it is necessary to keep an exception instance around
past the end of the except suite can be easily translated like so
try:
...
except E as N:
...
...
becomes
try:
...
except E as N:
n = N
...
…
This way, when N is deleted at the end of the block, n will persist
and can be used as normal.