Built-in Exception Classes

I didn’t really pull the prior section’s examples out of thin air. All built-in exceptions that Python itself may raise are predefined class objects. Moreover, they are organized into a shallow hierarchy with general superclass categories and specific subclass types, much like the exceptions class tree we developed earlier.

In Python 3.0, all the familiar exceptions you’ve seen (e.g., SyntaxError) are really just predefined classes, available as built-in names in the module named builtins (in Python 2.6, they instead live in __builtin__ and are also attributes of the standard library module exceptions). In addition, Python organizes the built-in exceptions into a hierarchy, to support a variety of catching modes. For example:

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

BaseException

The top-level root superclass of exceptions. This class is not supposed to be directly inherited by user-defined classes (use Exception instead). It provides default printing and state retention behavior inherited by subclasses. If the str built-in is called on an instance of this class (e.g., by print), the class returns the display strings of the constructor arguments passed when the instance was created (or an empty string if there were no arguments). In addition, unless subclasses replace this class’s constructor, all of the arguments passed to this class at instance construction time are stored in its args attribute as a tuple.

Exception

The top-level root superclass of application-related exceptions. This is an immediate subclass of BaseException and is superclass to every other built-in exception, except the system exit event classes (SystemExit, KeyboardInterrupt, and GeneratorExit). Almost all user-defined classes should inherit from this class, not BaseException. When this convention is followed, naming Exception in a try statement’s handler ensures that your program will catch everything but system exit events, which should normally be allowed to pass. In effect, Exception becomes a catchall in try statements and is more accurate than an empty except.

ArithmeticError

The superclass of all numeric errors (and a subclass of Exception).

OverflowError

A subclass of ArithmeticError that identifies a specific numeric error.

And so on—you can read further about this structure in reference texts such as Python Pocket Reference or the Python library manual. Note that the exceptions class tree differs slightly between Python 3.0 and 2.6. Also note that you can see the class tree in the help text of the exceptions module in Python 2.6 only (this module is removed in 3.0). See Chapters 4 and 15 for help on help:

>>> import exceptions
>>> help(exceptions)
...lots of text omitted...