8
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 ?

Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208

3 Answers3

8

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.

kindall
  • 178,883
  • 35
  • 278
  • 309
  • Can you also look at this question: http://stackoverflow.com/questions/39906375/multithreaded-file-read-python – Ankur Agarwal Oct 07 '16 at 19:13
  • 13
    On a side note, in Python 3, `e` is deleted before exiting the `except` clause: https://docs.python.org/3.3/reference/compound_stmts.html#except – Moses Koledoye Jul 16 '17 at 18:04
  • But you can save its value to another variable in the `except` clause: "This means the exception must be assigned to a different name to be able to refer to it after the except clause." – Dennis Williamson May 10 '23 at 17:09
2

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

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
sls
  • 21
  • 1
  • 3
2

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

libin
  • 420
  • 3
  • 7