内置异常

在 Python 中,所有异常都必须是类实例派生自 BaseException 。在 try 语句采用 except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.

The built-in exceptions listed in this chapter can be generated by the interpreter or built-in functions. Except where mentioned, they have an “associated value” indicating the detailed cause of the error. This may be a string or a tuple of several items of information (e.g., an error code and a string explaining the code). The associated value is usually passed as arguments to the exception class’s constructor.

User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition “just like” the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error.

The built-in exception classes can be subclassed to define new exceptions; programmers are encouraged to derive new exceptions from the Exception class or one of its subclasses, and not from BaseException . More information on defining exceptions is available in the Python Tutorial under 用户定义异常 .

异常上下文

Three attributes on exception objects provide information about the context in which the exception was raised:

BaseException. __context__
BaseException. __cause__
BaseException. __suppress_context__

When raising a new exception while another exception is already being handled, the new exception’s __context__ attribute is automatically set to the handled exception. An exception may be handled when an except or finally 子句,或 with statement, is used.

This implicit exception context can be supplemented with an explicit cause by using from with raise :

raise new_exc from original_exc