Page 227 - Beginning Programming with Pyth - John Paul Mueller
P. 227
2. Click Run Cell.
Python displays the expected exception text, as shown in Figure 10-
12.
FIGURE 10-12: Raising an exception requires only a call to raise.
Passing error information to the caller
Python provides exceptionally flexible error handling in that you can pass information to the caller (the code that is calling your code) no matter which exception you use. Of course, the caller may not know that the information is available, which leads to a lot of discussion on the topic. If you’re working with someone else’s code and don’t know whether additional information is available, you can always use the technique described in the “Obtaining a list of exception arguments” sidebar earlier in this chapter to find it.
You may have wondered whether you could provide better information when working with a ValueError exception than with an exception provided natively by Python. The following steps show that you can modify the output so that it does include helpful information.
1. Type the following code into the notebook — pressing Enter after
each line:
try:
Ex = ValueError()
Ex.strerror = "Value must be within 1 and 10." raise Ex
except ValueError as e:
print("ValueError Exception!", e.strerror)
The ValueError exception normally doesn’t provide an attribute named strerror (a common name for string error), but you can add it simply by assigning a value to it as shown. When the