同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库
Chapter 34. Exception Objects
So far, I’ve been deliberately vague about what an exception actually is. As suggested in the prior chapter, in Python 2.6 and 3.0 both built-in and user-defined exceptions are identified by class instance objects. Although this means you must use object-oriented programming to define new exceptions in your programs, classes and OOP in general offer a number of benefits.
Here are some of the advantages of class-based exceptions:
Because of these advantages, class-based exceptions support program evolution and larger systems well. In fact, all built-in exceptions are identified by classes and are organized into an inheritance tree, for the reasons just listed. You can do the same with user-defined exceptions of your own.
In Python 3.0, user-defined exceptions inherit from built-in exception superclasses. As we’ll see here, because these superclasses provide useful defaults for printing and state retention, the task of coding user-defined exceptions also involves understanding the roles of these built-ins.
Note
Version skew note: Python 2.6 and 3.0 both require exceptions to be defined by classes. In addition, 3.0 requires exception classes to be derived from the BaseException built-in exception superclass, either directly or indirectly. As we’ll see, most programs inherit from this class’s Exception subclass, to support catchall handlers for normal exception types—naming it in a handler will catch everything most programs should. Python 2.6 allows standalone classic classes to serve as exceptions, too, but it requires new-style classes to be derived from built-in exception classes, the same as 3.0.
请支持我们,让我们可以支付服务器费用。
使用微信支付打赏
