print(“TypeError: Please enter only numbers.”)
print(“ValueError: Invalid values, only numbers allowed.”)
#Capture any kind of errors
print(“Exception, Invalid values, only numbers allowed!”)
#print entered values
print(“Values Entered:”, x, y, z)
Traceback (most recent call last):
File “/Users/olicaluag/Downloads/errorhandling.py”, line 39, in
TypeError: test() missing 2 required positional arguments: ‘y’ and ‘z’
- If I received TypeError message, why it is not triggering the “except TypeError:”?
Because the “except TypeError” is inside the test() function, which
never even gets run because you’ve called it incorrectly.
You can catch it where you’re doing the call:
except TypeError as e:
print("bad use of test()", e)
- What possible mistake i can use to trigger “except Exception:”?
Cause some other exception type. You just outright “raise OSError()” or
some other exception.
The question itself says why we usually do not catch “Exception”: it
might be anything, and you don’t know what to do about it.
The general rule for exceptions is that you should only catch exceptions
which (a) you expect - your question says you don’t expect anything else
and (b) which you know can be “handled” with some specific action so
that the rest of the programme makes sense.
You should not try to catch other exceptions because that prevents you
getting a nice stack tract which at least tells you (a) what the
exception was and (b) where is happened and the call stack which led you
The purpose of try/except is not to make your programme never fall over
but to catch specific situations where the exceptional circumstance is
anticpated and has a meaningful response.
It may be helpful to think of exceptions as similar in purpose to
special return values indicating “not a valid result”. For example in C
or Go, where there are no exceptions, functions instead return various
“out of range” values. For example, many UNIX C API calls return -1 when
passed an invalid value. You’d catch that situation with an
The convenience of an exception is that you can decide where to catch
it. If you don’t know what to do with an exception you can just let it
out for something further out to deal with. Note that of course code too
far out won’t know enough to do something with it. But it avoids a
complex chain of if-statements at every call level to handle special
Cameron Simpson firstname.lastname@example.org