Python 2和3中捕获的异常实例的范围 [英] Scope of caught exception instance in Python 2 and 3
问题描述
由于Python变量可以在其循环之外访问,并且 try
--
块除外,因此我天真的认为这下面的代码段可以正常工作,因为可以访问 e
:
Since in Python variables are accessible outside of their loops and try
-except
blocks, I naively thought that this code snippet below would work fine because e
would be accessible:
try:
int('s')
except ValueError as e:
pass
print(e)
在Python 2(经过2.7测试)中,它确实按预期工作,输出为:
In Python 2 (2.7 tested), it does work as I expected and the output is:
invalid literal for int() with base 10: 's'
但是,在Python 3让我惊讶的是输出是:
However, in Python 3 I was surprised that the output is:
NameError: name 'e' is not defined
为什么?
推荐答案
后来我找到了答案,因为 PEP 3110 解释说在Python 3中名称在 except
套件的末尾删除,以实现更有效的垃圾收集。如果您希望避免这种情况的发生,还建议使用语法:
I later found an answer as PEP 3110 explains that in Python 3 the caught name is removed at the end of the except
suite to enable more efficient garbage collection. There is also recommended syntax if you wish to avoid this occurring:
需要在
附近保持异常实例的情况
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:
...
...
try:
...
except E as N:
n = N
...
…
这样,当N的末尾被删除时块,n将保留
并可以正常使用。
This way, when N is deleted at the end of the block, n will persist and can be used as normal.
这篇关于Python 2和3中捕获的异常实例的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!