7
votes
while True:
  try:
    2/0
  except Exception as e:
    break

print e      

Gives: integer division or modulo by zero

I thought scope of e is within the while block and it will not be accessible in the outside print statement. What did I miss ?

3
Of course, you should only use e within the except, simply because it doesn't exist (or is something different) if you never hit the exception. - Kenny Ostrom
@KennyOstrom good point. - Ankur Agarwal

3 Answers

7
votes

Simple: while does not create a scope in Python. Python has only the following scopes:

  • function scope (may include closure variables)
  • class scope (only while the class is being defined)
  • global (module) scope
  • comprehension/generator expression scope

So when you leave the while loop, e, being a local variable (if the loop is in a function) or a global variable (if not), is still available.

tl;dr: Python is not C.

2
votes

in except ... as e, the e will be drop when Jump out of try except, Whether or not it was defined before.

When an exception has been assigned using as target, it is cleared at the end of the except clause.

refer to offical website link: https://docs.python.org/3/reference/compound_stmts.html#the-try-statement

1
votes

I just ran across something similar. The as in the except does not behave as expected:

#!/usr/bin/python3.6

exc = 'foofoo'
print('exc in locals?', 'exc' in locals())
try:
  x = 1 / 0
except Exception as exc:
  print('exc in locals?', 'exc' in locals())
  print('Error', exc)
print('exc in locals?', 'exc' in locals())
print('Sorry, got an exception', exc)

This results in the following output. NameError is indicates that exc is no longer in locals().

% ./g.py 
exc in locals? True
exc in locals? True
Error division by zero
exc in locals? False
Traceback (most recent call last):
  File "./g.py", line 11, in <module>
    print('Sorry, got an exception', exc)
NameError: name 'exc' is not defined
% 

The as ex removed the the variable from the scope. I have not been found the explanation for this. This code produces the expected output:

#!/usr/bin/python3.6

exc = 'foofoo'
print('exc in locals?', 'exc' in locals())
try:
  x = 1 / 0
except Exception as exc_:
  exc = str(exc_)
  print('exc in locals?', 'exc' in locals())
  print('Error, exc)
print('exc in locals?', 'exc' in locals())
print('Sorry, got an exception', exc)

This explains the observed behavior:Python 3 try statement