0

When a variable is created by except ... as variable, one cannot access the variable from outside of except block. Why is it happening? The only way to access the value of variable I've found is to assign it to another variable:

c = 10
try:
    d = c[0]
except Exception as err:
    b = err

print(b)
print(err)

print(b) shows error message: "'int' object is not subscriptable". But print(err) raises "NameError: name 'err' is not defined".

So, the question is: why is the variable "err" gone?

Alexei
  • 1
  • It's just designed this way. The `thing` in `for thing in collection:` will leak into outer scope, but `err` in exception handling doesn't. – ForceBru Nov 30 '20 at 12:31
  • Yes, this is [documented here](https://docs.python.org/3.3/reference/compound_stmts.html#except). It's an ugly solution to a potential memory leak. – juanpa.arrivillaga Nov 30 '20 at 12:50

0 Answers0