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.