Exception instance scope in Python 2 and 3

Since in Python variables are available outside of their loops and blocks try

- except

I naively thought that this piece of code below would work fine because it e

would be available:

try:
    int('s')
except ValueError as e:
    pass
print(e)

      

In Python 2 (2.7 tested) it works as I expected and the output is:

invalid literal for int() with base 10: 's'

      

However, in Python 3, I was surprised that the output is:

NameError: name 'e' is not defined

      

Why is this?

+3


source to share


1 answer


Later I found the answer as PEP 3110 explains that in Python 3 the caught name is removed at the end of the set except

to allow for more efficient garbage collection. It is also recommended to use the syntax if you want to avoid this:



Situations in which it is necessary to keep an exception instance around past the end of the except packet can be easily translated like this

try:
    ...
except E as N:
    ...
...

      

becomes

try:
    ...
except E as N:
    n = N
    ...


      

Thus, when N is removed at the end of a block, n will be preserved and can be used as usual.

+5


source







All Articles