Page 228 - Beginning Programming with Pyth - John Paul Mueller
P. 228

example raises the exception, the except clause handles it as usual but obtains access to the attributes using e. You can then access the e.strerror member to obtain the added information.
2. Click Run Cell.
Python displays an expanded ValueError exception, as shown in
Figure 10-13.
  FIGURE 10-13: You can add error information to any exception.
Creating and Using Custom Exceptions
Python provides a wealth of standard exceptions that you should use whenever possible. These exceptions are incredibly flexible, and you can even modify them as needed (within reason) to meet specific needs. For example, the “Passing error information to the caller” section of this chapter demonstrates how to modify a ValueError exception to allow for additional data. However, sometimes you simply must create a custom exception because none of the standard exceptions will work. Perhaps the exception name just doesn’t tell the viewer the purpose that the exception serves. You may need a custom exception for specialized database work or when working with a service.
The example in this section is going to seem a little complicated for now because you haven’t worked with classes before. Chapter 15 introduces you to classes and helps you understand how they work. If you want to skip this section until after you read Chapter 15, you can do so without any problem.
The example in this section shows a quick method for creating your own exceptions. To perform this task, you must create a class that uses an
     

























































































   226   227   228   229   230