The standard way by which Python "handles" exceptions is by throwing an error of some sort. If the program is not coded to "catch" the error and do something with it, the program usually crashes, as we saw earlier. However, even if the program works just as you intended, you can program in your own exceptions using the raise statement.
At a Python shell, type the following:
You will get feedback from the Python interpreter that looks like this:
>>> raise NameError Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError
You can use any kind of error that is included in the module exceptions (for a full list of exceptions, see the page of exceptions). You can also raise your own exceptions (see below). However, the exception raised must be a class or an instance of a class. Anything else will result in a TypeError. If you want to see what would happen, type the following at a Python shell prompt:
Whenever an exception is raised in the code, Python will raise that error -- even if it sees nothing wrong. In this way, your programs can be stricter than the Python interpreter. Say, for example, you have a set of options and would like a NameError error to be thrown if the user chooses an option not listed. Python will do that as part of the exception handling process, instead of throwing a KeyError or something similar.