0

I'm completely baffled by this one, and couldn't find anything about it.

I wanted to catch an exception and then later do something different if one had occurred, so I wrote code like this:

x = 1
for i in range(5, -1, -1):
    error = None
    try:
        x = x / i
    except Exception as error:
        print(error)
    if error is None:
        print(f"x={x}: No problem")

The above code catches the deliberate exception but then raises a NameError afterwards:

x=0.2: No problem
x=0.05: No problem
x=0.016666666666666666: No problem
x=0.008333333333333333: No problem
x=0.008333333333333333: No problem
float division by zero
Traceback (most recent call last):
  File "/home/pi/code/temp-control/test.py", line 8, in <module>
    if error is None:
NameError: name 'error' is not defined

I can avoid the problem by not using the same name for the variable used to catch the exception and the variable to flag that an error occurred:

x = 1
for i in range(5, -1, -1):
    error = None
    try:
        x = x / i
    except Exception as err:
        print(err)
        error = True
    if error is None:
        print(f"x={x}: No problem")

but I still don't understand how the NameError even occurs in the first version. The name error seems to get deleted by the try .. except .. clause.

sj95126
  • 6,520
  • 2
  • 15
  • 34
Bill
  • 10,323
  • 10
  • 62
  • 85
  • Thanks. I did not know that. Would be nice if the variable in the local scope wasn't eliminated in the process! I don't think this occurs with list comprehensions or context managers (they either leave the local variable intact or reassign it). – Bill Nov 20 '21 at 05:23
  • 2
    Use the `else` clouse instead of `if err is None` to execute code when there's no error. – kindall Nov 20 '21 at 05:23
  • specifically the PEP which calls out this change: https://www.python.org/dev/peps/pep-3110/#semantic-changes – anthony sottile Nov 20 '21 at 05:46

0 Answers0