Page 226 - Beginning Programming with Pyth - John Paul Mueller
P. 226
Raising Exceptions
So far, the examples in this chapter have reacted to exceptions. Something happens and the application provides error-handling support for that event. However, situations arise for which you may not know how to handle an error event during the application design process. Perhaps you can’t even handle the error at a particular level and need to pass it up to some other level to handle. In short, in some situations, your application must generate an exception. This act is called raising (or sometimes throwing) the exception. The following sections describe common scenarios in which you raise exceptions in specific ways.
Raising exceptions during exceptional conditions
The example in this section demonstrates how you raise a simple exception — that it doesn’t require anything special. The following steps simply create the exception and then handle it immediately.
1. Type the following code into the notebook — pressing Enter after
each line:
try:
raise ValueError
except ValueError:
print("ValueError Exception!")
You wouldn’t ever actually create code that looks like this, but it shows you how raising an exception works at its most basic level. In this case, the raise call appears within a try...except block. A basic raise call simply provides the name of the exception to raise (or throw). You can also provide arguments as part of the output to provide additional information.
Notice that this try...except block lacks an else clause because there is nothing to do after the call. Although you rarely use a try...except block in this manner, you can. You may encounter situations like this one sometimes and need to remember that adding the else clause is purely optional. On the other hand, you must add at least one except clause.