why my excepts are not executing?
They look ok to me. Maybe x, y and z are all valid strings representing
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:
print("som other unspecified exception")
print("You have provided valid values")
otherwise the try/except is also testing the “valid values” print().
Not normally what people intend.
These are valid ints: int(9) == 9
This should fire your second except: int(“a”) should raise a ValueError.
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
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):
except NameError as e:
print("Name Error!", e)
That way you get some information about what, specificly, was bad.
And a “bare 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
Sometimes you need to catch more than you can handle. Example:
f = open("filename")
except OSError as e:
if e.errno == errno.ENOENT:
print("missing file, but that is ok")
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.
Cameron Simpson email@example.com