Chapter 35. Exception Objects
So far, this book has been somewhat vague about what an exception actually is. This chapter clears up the mystery by disclosing the facts behind exception objects—both built-in and user-defined. As suggested in the preceding chapters, exceptions are identified by class instance objects. This is what is raised and propagated along by exception processing, and the source of the class matched against except clauses in try statements.
Although this means you must use object-oriented programming to define new exceptions in your programs—and introduces a knowledge dependency lamented in the prior chapter’s note—basing exceptions on classes and OOP offers a number of benefits. Among them, class-based exceptions support:
- Flexible exception categories
Exception classes allow code to choose specificity and ease future changes. Adding new exception subclasses, for example, need not require changes in
trystatements.- State information and behavior
Exception classes provide a natural place to store context for use in the
tryhandler. Both attributes and methods, for example, are available on the raised instance.- Reuse by inheritance
Exceptions classes can participate in inheritance hierarchies to obtain and customize common behavior. Inherited error displays, for example, can provide a common look and feel.
Because of these advantages, class-based exceptions support program evolution and larger systems well. As you’ll learn here, all built-in exceptions are identified ...