在 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 below 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
用户定义异常
.
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
The expression following
from
must be an exception or
None
. It will be set as
__cause__
on the raised exception. Setting
__cause__
also implicitly sets the
__suppress_context__
属性为
True
, so that using
raise new_exc from None
effectively replaces the old exception with the new one for display purposes (e.g. converting
KeyError
to
AttributeError
), while leaving the old exception available in
__context__
for introspection when debugging.
The default traceback display code shows these chained exceptions in addition to the traceback for the exception itself. An explicitly chained exception in
__cause__
is always shown when present. An implicitly chained exception in
__context__
is shown only if
__cause__
is
None
and
__suppress_context__
为 False。
In either case, the exception itself is always shown after any chained exceptions so that the final line of the traceback always shows the last exception that was raised.
User code can create subclasses that inherit from an exception type. It’s recommended to only subclass one exception type at a time to avoid any possible conflicts between how the bases handle the
args
attribute, as well as due to possible memory layout incompatibilities.
CPython 实现细节: Most built-in exceptions are implemented in C for efficiency, see: Objects/exceptions.c . Some have custom memory layouts which makes it impossible to create a subclass that inherits from multiple exception types. The memory layout of a type is an implementation detail and might change between Python versions, leading to new conflicts in the future. Therefore, it’s recommended to avoid subclassing multiple exception types altogether.
以下异常主要用作其它异常的基类。
The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use
Exception
)。若
str()
is called on an instance of this class, the representation of the argument(s) to the instance are returned, or the empty string when there were no arguments.
The tuple of arguments given to the exception constructor. Some built-in exceptions (like
OSError
) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.
此方法设置
tb
as the new traceback for the exception and returns the exception object. It was more commonly used before the exception chaining features of
PEP 3134
became available. The following example shows how we can convert an instance of
SomeException
into an instance of
OtherException
while preserving the traceback. Once raised, the current frame is pushed onto the traceback of the
OtherException
, as would have happened to the traceback of the original
SomeException
had we allowed it to propagate to the caller.
try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb)
Add the string
note
to the exception’s notes which appear in the standard traceback after the exception string. A
TypeError
被引发若
note
is not a string.
3.11 版新增。
A list of the notes of this exception, which were added with
add_note()
. This attribute is created when
add_note()
被调用。
3.11 版新增。
所有内置、非系统退出异常都派生自此类。所有用户定义异常也应派生自此类。
The base class for those built-in exceptions that are raised for various arithmetic errors:
OverflowError
,
ZeroDivisionError
,
FloatingPointError
.
The base class for the exceptions that are raised when a key or index used on a mapping or sequence is invalid:
IndexError
,
KeyError
. This can be raised directly by
codecs.lookup()
.
以下异常是通常引发的异常。
被引发当属性引用 (见
属性引用
) 或赋值失败。(当对象根本不支持属性引用或属性赋值时,
TypeError
被引发)。
name
and
obj
attributes can be set using keyword-only arguments to the constructor. When set they represent the name of the attribute that was attempted to be accessed and the object that was accessed for said attribute, respectively.
3.10 版改变:
添加
name
and
obj
属性。
被引发当
input()
function hits an end-of-file condition (EOF) without reading any data. (N.B.: the
io.IOBase.read()
and
io.IOBase.readline()
methods return an empty string when they hit EOF.)
目前不使用。
被引发当
generator
or
协程
被关闭;见
generator.close()
and
coroutine.close()
。它直接继承自
BaseException
而不是
Exception
由于它在技术上不是错误。
被引发当
import
statement has troubles trying to load a module. Also raised when the “from list” in
from ... import
has a name that cannot be found.
name
and
path
attributes can be set using keyword-only arguments to the constructor. When set they represent the name of the module that was attempted to be imported and the path to any file which triggered the exception, respectively.
3.3 版改变:
添加
name
and
path
属性。
子类化的
ImportError
其被引发通过
import
当定位不到模块时。它也被引发当
None
发现于
sys.modules
.
3.6 版新增。
被引发当在现有键集中找不到映射 (字典) 键时。
被引发当用户命中中断键时 (通常
Control
-
C
or
删除
)。在执行期间,会定期检查中断。异常继承自
BaseException
以免被意外捕获通过代码捕获
Exception
从而防止解释器退出。
注意
捕获
KeyboardInterrupt
需要特殊考虑。因为可以在不可预测点引发它,所以有时,它可能离开正运行程序在不一致状态情况下。一般来说,最好允许
KeyboardInterrupt
尽快结束程序,或完全避免引发它 (见
有关信号处理程序和异常的注意事项
)。
被引发当操作耗尽内存但情况仍可以挽救 (通过删除一些对象)。关联值是指示哪种 (内部) 操作耗尽内存的字符串。注意,由于底层内存管理体系结构(C 的
malloc()
函数),解释器可能并不会总是能够从这种情况完全恢复;尽管如此,它会引发异常,以便在程序失控的情况下打印堆栈回溯。
被引发当找不到局部 (或全局) 名称时。这仅适用于不合格名称。关联值是包括找不到名称的错误消息。
name
属性可以使用构造函数的仅关键词自变量设置。当设置时,它表示试图访问的变量名称。
3.10 版改变:
添加
name
属性。
此异常派生自
RuntimeError
。在用户定义的基类中,抽象方法应引发此异常当它们要求派生类覆盖方法时,或者当在开发类指示仍然需要添加真正实现时。
注意
它不应该被用于指示意味着根本不支持的运算符 (或方法) – 在这种情况下,要么不定义运算符 (或方法),要么若是子类,则将它设为
None
.
注意
NotImplementedError
and
NotImplemented
不可互换,即使它们拥有相似的名称和用途。见
NotImplemented
了解使用时的有关细节。
此异常被引发当系统函数返回系统相关错误时,包括 I/O 故障,譬如 file not found 或 disk full (不针对非法自变量类型或其它偶然错误)。
构造函数的第 2 种形式设置相应属性,描述见下文。属性默认为
None
若未指定。为向后兼容,若有传递 3 个自变量,
args
属性是包含仅前 2 构造函数自变量的 2 元素元组。
构造函数经常实际返回子类化的
OSError
,作为描述在
OS 异常
下文。特定子类从属最终
errno
值。此行为才发生当构造
OSError
直接或凭借别名,且不被继承当子类化时。
数值错误代码来自 C 变量
errno
.
在 Windows,这给出本机 Windows 错误代码。
errno
属性那么是按 POSIX 术语的本机错误代码的近似翻译。
在 Windows,若
winerror
构造函数自变量是整数,
errno
属性由 Windows 错误代码确定,和
errno
自变量被忽略。在其它平台,
winerror
自变量被忽略,和
winerror
属性不存在。
相应的错误消息,由操作系统提供。它被格式化由 C 函数
perror()
在 POSIX (便携式操作系统接口),和
FormatMessage()
在 Windows。
对于涉及文件系统路径的异常 (譬如
open()
or
os.unlink()
),
filename
是传递给函数的文件名。对于涉及 2 个文件系统路径的函数 (譬如
os.rename()
),
filename2
相当于传递给函数的第 2 文件名。
3.3 版改变:
EnvironmentError
,
IOError
,
WindowsError
,
socket.error
,
select.error
and
mmap.error
已合并成
OSError
,且构造函数可能返回子类。
3.4 版改变:
filename
属性现在是传递给函数的原始文件名,而不是编码名称或名称解码自
文件系统编码和错误处理程序
。另外,
filename2
构造函数自变量和属性的添加。
被引发当算术运算的结果太大不能表示时。这不会发生对于整数 (其宁愿引发
MemoryError
而不是放弃)。不管怎样,由于历史原因,有时会为超出要求范围的整数引发 OverflowError。因为 C 缺乏浮点异常处理的标准化,所以大多数浮点运算都不校验。
此异常派生自
RuntimeError
。它被引发当解释器检测到最大递归深度 (见
sys.getrecursionlimit()
) 超过。
3.5 版新增:
先前,纯
RuntimeError
被引发。
此异常被引发当弱引用代理时,创建通过
weakref.proxy()
函数,用于访问所指属性在它被垃圾收集之后。有关弱引用的更多信息,见
weakref
模块。
被引发当检测到不属于任何其它类别的错误时。关联值是指示哪里准确出错的字符串。
被引发通过内置函数
next()
和
iterator
's
__next__()
方法以发出迭代器没有进一步项产生的信号。
异常对象拥有单属性
value
,其作为自变量给出当构造异常时,且默认为
None
.
当
generator
or
协程
函数返回,新的
StopIteration
实例被引发,并将由函数返回的值用作
value
参数用于异常构造函数。
若生成器代码直接 (或间接) 引发
StopIteration
,它被转换成
RuntimeError
(保留
StopIteration
作为新异常的原因)。
3.3 版改变:
添加
value
属性和生成器函数能力以使用它来返回值。
3.5 版改变:
引入 RuntimeError 变换凭借
from __future__ import generator_stop
,见
PEP 479
.
3.7 版改变:
启用
PEP 479
对于默认情况下的所有代码:
StopIteration
在生成器中引发的错误被变换成
RuntimeError
.
被引发当剖析器遇到句法错误时。这可能发生在
import
语句,在调用内置函数
compile()
,
exec()
,或
eval()
,或当读取初始脚本或标准输入 (也交互) 时。
str()
为异常实例仅返回错误消息。详细信息是其成员还可用作单独属性的元组。
发生句法错误的文件名。
Which line number in the file the error occurred in. This is 1-indexed: the first line in the file has a
lineno
of 1.
The column in the line where the error occurred. This is 1-indexed: the first character in the line has an
offset
of 1.
错误中涉及的源代码文本。
Which line number in the file the error occurred ends in. This is 1-indexed: the first line in the file has a
lineno
of 1.
The column in the end line where the error occurred finishes. This is 1-indexed: the first character in the line has an
offset
of 1.
For errors in f-string fields, the message is prefixed by “f-string: ” and the offsets are offsets in a text constructed from the replacement expression. For example, compiling f’Bad {a b} field’ results in this args attribute: (‘f-string: …’, (‘’, 1, 2, ‘(a b)n’, 1, 5)).
3.10 版改变:
添加
end_lineno
and
end_offset
属性。
不正确缩进相关句法错误的基类。这是子类化的
SyntaxError
.
Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of
IndentationError
.
Raised when the interpreter finds an internal error, but the situation does not look so serious to cause it to abandon all hope. The associated value is a string indicating what went wrong (in low-level terms).
You should report this to the author or maintainer of your Python interpreter. Be sure to report the version of the Python interpreter (
sys.version
; it is also printed at the start of an interactive Python session), the exact error message (the exception’s associated value) and if possible the source of the program that triggered the error.
此异常被引发通过
sys.exit()
函数。它继承自
BaseException
而不是
Exception
so that it is not accidentally caught by code that catches
Exception
. This allows the exception to properly propagate up and cause the interpreter to exit. When it is not handled, the Python interpreter exits; no stack traceback is printed. The constructor accepts the same optional argument passed to
sys.exit()
. If the value is an integer, it specifies the system exit status (passed to C’s
exit()
function); if it is
None
, the exit status is zero; if it has another type (such as a string), the object’s value is printed and the exit status is one.
调用
sys.exit()
is translated into an exception so that clean-up handlers (
finally
clauses of
try
statements) can be executed, and so that a debugger can execute a script without running the risk of losing control. The
os._exit()
function can be used if it is absolutely positively necessary to exit immediately (for example, in the child process after a call to
os.fork()
).
传递给构造函数的退出状态或错误消息。(默认为
None
)。
被引发当操作 (或函数) 被应用于不适当类型的对象时。关联值是字符串,给出类型不匹配的有关细节。
此异常可能由用户代码引发,以指示不支持且不意味着支持对象所尝试的操作。若对象意味着支持给定操作但尚未提供实现,
NotImplementedError
是要引发的适当异常。
Passing arguments of the wrong type (e.g. passing a
list
when an
int
is expected) should result in a
TypeError
, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a
ValueError
.
Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. This is a subclass of
NameError
.
被引发当发生 Unicode 相关编码或解码错误时。它是子类化的
ValueError
.
UnicodeError
拥有描述编码 (或解码) 错误的属性。例如,
err.object[err.start:err.end]
gives the particular invalid input that the codec failed on.
引发错误的编码名称。
描述特定编解码器错误的字符串。
试图编码 (或解码) 的编解码器对象。
Raised when a Unicode-related error occurs during encoding. It is a subclass of
UnicodeError
.
Raised when a Unicode-related error occurs during decoding. It is a subclass of
UnicodeError
.
Raised when a Unicode-related error occurs during translating. It is a subclass of
UnicodeError
.
被引发当操作 (或函数) 收到类型正确但值不合适的自变量,且未按更准确异常描述这种情况,譬如
IndexError
.
被引发当除法 (或模) 运算的第 2 自变量为 0。关联值是指示操作数和运算类型的字符串。
保留下列异常是为兼容先前版本;从 Python 3.3 开始,它们是别名化的
OSError
.
Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to
errno
EAGAIN
,
EALREADY
,
EWOULDBLOCK
and
EINPROGRESS
.
In addition to those of
OSError
,
BlockingIOError
可以拥有更多属性:
An integer containing the number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the
io
模块。
连接相关问题的基类。
子类
BrokenPipeError
,
ConnectionAbortedError
,
ConnectionRefusedError
and
ConnectionResetError
.
子类化的
ConnectionError
, raised when trying to write on a pipe while the other end has been closed, or trying to write on a socket which has been shutdown for writing. Corresponds to
errno
EPIPE
and
ESHUTDOWN
.
子类化的
ConnectionError
,被引发当对等方中止连接尝试时。相当于
errno
ECONNABORTED
.
子类化的
ConnectionError
, raised when a connection attempt is refused by the peer. Corresponds to
errno
ECONNREFUSED
.
子类化的
ConnectionError
, raised when a connection is reset by the peer. Corresponds to
errno
ECONNRESET
.
Raised when trying to create a file or directory which already exists. Corresponds to
errno
EEXIST
.
Raised when a file or directory is requested but doesn’t exist. Corresponds to
errno
ENOENT
.
Raised when a system call is interrupted by an incoming signal. Corresponds to
errno
EINTR
.
3.5 版改变:
Python now retries system calls when a syscall is interrupted by a signal, except if the signal handler raises an exception (see
PEP 475
for the rationale), instead of raising
InterruptedError
.
被引发当文件操作 (譬如
os.remove()
) 请求目录。相当于
errno
EISDIR
.
被引发当目录操作 (譬如
os.listdir()
) is requested on something which is not a directory. On most POSIX platforms, it may also be raised if an operation attempts to open or traverse a non-directory file as if it were a directory. Corresponds to
errno
ENOTDIR
.
Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to
errno
EACCES
and
EPERM
.
被引发当系统函数在系统级超时时。相当于
errno
ETIMEDOUT
.
3.3 版新增:
所有以上
OSError
子类被添加。
另请参阅
PEP 3151 - 返工 OS 和 IO 异常层次结构
下列异常被用作警告类别;见 警告类别 文档编制了解更多细节。
警告类别的基类。
由用户代码生成的警告的基类。
Base class for warnings about deprecated features when those warnings are intended for other Python developers.
Ignored by the default warning filters, except in the
__main__
模块 (
PEP 565
). Enabling the
Python 开发模式
展示此警告。
The deprecation policy is described in PEP 387 .
Base class for warnings about features which are obsolete and expected to be deprecated in the future, but are not deprecated at the moment.
This class is rarely used as emitting a warning about a possible upcoming deprecation is unusual, and
DeprecationWarning
is preferred for already active deprecations.
Ignored by the default warning filters. Enabling the Python 开发模式 展示此警告。
The deprecation policy is described in PEP 387 .
Base class for warnings about dubious syntax.
Base class for warnings about dubious runtime behavior.
Base class for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python.
Base class for warnings about probable mistakes in module imports.
Ignored by the default warning filters. Enabling the Python 开发模式 展示此警告。
Base class for warnings related to Unicode.
Base class for warnings related to encodings.
见 选择加入 EncodingWarning 了解细节。
3.10 版新增。
用于资源使用情况的相关警告基类。
Ignored by the default warning filters. Enabling the Python 开发模式 展示此警告。
3.2 版新增。
The following are used when it is necessary to raise multiple unrelated exceptions. They are part of the exception hierarchy so they can be handled with
except
like all other exceptions. In addition, they are recognised by
except*
, which matches their subgroups based on the types of the contained exceptions.
Both of these exception types wrap the exceptions in the sequence
excs
。
msg
parameter must be a string. The difference between the two classes is that
BaseExceptionGroup
extends
BaseException
and it can wrap any exception, while
ExceptionGroup
extends
Exception
and it can only wrap subclasses of
Exception
. This design is so that
except Exception
catches an
ExceptionGroup
而非
BaseExceptionGroup
.
BaseExceptionGroup
constructor returns an
ExceptionGroup
rather than a
BaseExceptionGroup
if all contained exceptions are
Exception
instances, so it can be used to make the selection automatic. The
ExceptionGroup
constructor, on the other hand, raises a
TypeError
if any contained exception is not an
Exception
子类。
msg
自变量用于构造函数。这是只读属性。
A tuple of the exceptions in the
excs
sequence given to the constructor. This is a read-only attribute.
Returns an exception group that contains only the exceptions from the current group that match
条件
,或
None
if the result is empty.
The condition can be either a function that accepts an exception and returns true for those that should be in the subgroup, or it can be an exception type or a tuple of exception types, which is used to check for a match using the same check that is used in an
except
子句。
The nesting structure of the current exception is preserved in the result, as are the values of its
message
,
__traceback__
,
__cause__
,
__context__
and
__notes__
fields. Empty nested groups are omitted from the result.
The condition is checked for all exceptions in the nested exception group, including the top-level and any nested exception groups. If the condition is true for such an exception group, it is included in the result in full.
像
subgroup()
,但返回一对
(match, rest)
where
match
is
subgroup(condition)
and
rest
is the remaining non-matching part.
Returns an exception group with the same
message
,
__traceback__
,
__cause__
,
__context__
and
__notes__
but which wraps the exceptions in
excs
.
此方法用于
subgroup()
and
split()
. A subclass needs to override it in order to make
subgroup()
and
split()
return instances of the subclass rather than
ExceptionGroup
.
>>> class MyGroup(ExceptionGroup): ... def derive(self, exc): ... return MyGroup(self.message, exc) ... >>> MyGroup("eg", [ValueError(1), TypeError(2)]).split(TypeError) (MyGroup('eg', [TypeError(2)]), MyGroup('eg', [ValueError(1)]))
注意,
BaseExceptionGroup
定义
__new__()
, so subclasses that need a different constructor signature need to override that rather than
__init__()
. For example, the following defines an exception group subclass which accepts an exit_code and and constructs the group’s message from it.
class Errors(ExceptionGroup): def __new__(cls, errors, exit_code): self = super().__new__(Errors, f"exit code: {exit_code}", errors) self.exit_code = exit_code return self def derive(self, excs): return Errors(excs, self.exit_code)
3.11 版新增。
内置异常的类层次结构:
BaseException
├── BaseExceptionGroup
├── GeneratorExit
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ExceptionGroup [BaseExceptionGroup]
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── BlockingIOError
│ ├── ChildProcessError
│ ├── ConnectionError
│ │ ├── BrokenPipeError
│ │ ├── ConnectionAbortedError
│ │ ├── ConnectionRefusedError
│ │ └── ConnectionResetError
│ ├── FileExistsError
│ ├── FileNotFoundError
│ ├── InterruptedError
│ ├── IsADirectoryError
│ ├── NotADirectoryError
│ ├── PermissionError
│ ├── ProcessLookupError
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
│ ├── NotImplementedError
│ └── RecursionError
├── StopAsyncIteration
├── StopIteration
├── SyntaxError
│ └── IndentationError
│ └── TabError
├── SystemError
├── TypeError
├── ValueError
│ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
│ └── UnicodeTranslateError
└── Warning
├── BytesWarning
├── DeprecationWarning
├── EncodingWarning
├── FutureWarning
├── ImportWarning
├── PendingDeprecationWarning
├── ResourceWarning
├── RuntimeWarning
├── SyntaxWarning
├── UnicodeWarning
└── UserWarning