why my excepts are not executing?
They look ok to me. Maybe x, y and z are all valid strings representing
ints?
def TestNumbers(x,y,z):
try:
X = int(x)
y = int(y)
z = int(z)
print(‘You have provided valid values’)
BTW, I would put this print in the else part of the try/except:
try:
....
except NameError:
print("NameError")
except:
print("som other unspecified exception")
else:
print("You have provided valid values")
otherwise the try/except is also testing the “valid values” print().
Not normally what people intend.
print(TestNumbers(5,6,8))
These are valid ints: int(9) == 9
print(TestNumbers(“a”,5,8))
This should fire your second except: int(“a”) should raise a ValueError.
print(TestNumbers(a,6,7))
I don’t see a definition for the variable named “a”.
Note that the NameError this causes will happen before calling
TestNumbers, so the try/except won’t see it, as the try/except never
even runs.
Besides, you rarely want to catch NameError - it almost always indicates
an error in your programme logic, not invalid data to process.
Finally, it is almost always best to report the exception you catch (if
you don’t handle it):
try:
....
except NameError as e:
print("Name Error!", e)
That way you get some information about what, specificly, was bad.
And a “bare except”:
except:
is also usually a bad idea: it catches anything. Normal practice is to
catch only things for which you have a well defined action to recover
from. That way unexpected (and unhandled) exceptions get out and provide
a nice traceback showing how the code was called, which helps you debug
the situation.
Sometimes you need to catch more than you can handle. Example:
try:
f = open("filename")
except OSError as e:
if e.errno == errno.ENOENT:
print("missing file, but that is ok")
else:
raise
else:
process the file f here ...
Here we have a look at a broad class of error, and recognise a specific
special circumstance which is ok (missing file? pretend it is empty).
Otherwise we reraise the exception as though it had never been caught in
the “else:” part of the if-statement.
Cheers,
Cameron Simpson cs@cskk.id.au