在 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
用户定义异常
.
当引发 (或重新引发) 异常在
except
or
finally
clause
__context__
is automatically set to the last exception caught; if the new exception is not handled the traceback that is eventually displayed will include the originating exception(s) and the final exception.
When raising a new exception (rather than using a bare
raise
to re-raise the exception currently being handled), the 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.
以下异常主要用作其它异常的基类。
BaseException
¶
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.
args
¶
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.
with_traceback
(
tb
)
¶
此方法设置 tb as the new traceback for the exception and returns the exception object. It is usually used in exception handling code like this:
try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb)
Exception
¶
所有内置、非系统退出异常都派生自此类。所有用户定义异常也应派生自此类。
ArithmeticError
¶
The base class for those built-in exceptions that are raised for various arithmetic errors:
OverflowError
,
ZeroDivisionError
,
FloatingPointError
.
LookupError
¶
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()
.
以下异常是通常引发的异常。
EOFError
¶
被引发当
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.)
FloatingPointError
¶
Raised when a floating point operation fails. This exception is always defined, but can only be raised when Python is configured with the
--with-fpectl
option, or the
WANT_SIGFPE_HANDLER
symbol is defined in the
pyconfig.h
文件。
GeneratorExit
¶
被引发当
generator
or
协程
被关闭;见
generator.close()
and
coroutine.close()
。它直接继承自
BaseException
而不是
Exception
由于它在技术上不是错误。
ImportError
¶
被引发当
import
statement fails to find the module definition or when a
from ... import
fails to find a name that is to be imported.
The
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
属性。
KeyError
¶
被引发当在现有键集中找不到映射 (字典) 键时。
KeyboardInterrupt
¶
被引发当用户命中中断键时 (通常
Control-C
or
Delete
)。在执行期间,会定期检查中断。异常继承自
BaseException
以免被意外捕获通过代码捕获
Exception
从而防止解释器退出。
MemoryError
¶
被引发当操作耗尽内存但情况仍可以挽救 (通过删除一些对象)。关联值是指示哪种 (内部) 操作耗尽内存的字符串。注意,由于底层内存管理体系结构(C 的
malloc()
函数),解释器可能并不会总是能够从这种情况完全恢复;尽管如此,它会引发异常,以便在程序失控的情况下打印堆栈回溯。
NameError
¶
被引发当找不到局部 (或全局) 名称时。这仅适用于不合格名称。关联值是包括找不到名称的错误消息。
NotImplementedError
¶
此异常派生自
RuntimeError
. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.
OSError
(
[
arg
]
)
¶
OSError
(
errno
,
strerror
[
,
filename
[
,
winerror
[
,
filename2
]
]
]
)
此异常被引发当系统函数返回系统相关错误时,包括 I/O 故障,譬如 file not found 或 disk full (不针对非法自变量类型或其它偶然错误)。
构造函数的第 2 种形式设置相应属性,描述见下文。属性默认为
None
若未指定。为向后兼容,若有传递 3 个自变量,
args
属性是包含仅前 2 构造函数自变量的 2 元素元组。
构造函数经常实际返回子类化的
OSError
,作为描述在
OS 异常
下文。特定子类从属最终
errno
值。此行为才发生当构造
OSError
直接或凭借别名,且不被继承当子类化时。
errno
¶
数值错误代码来自 C 变量
errno
.
winerror
¶
在 Windows,这给出本机 Windows 错误代码。
errno
属性那么是按 POSIX 术语的本机错误代码的近似翻译。
在 Windows,若
winerror
构造函数自变量是整数,
errno
属性由 Windows 错误代码确定,和
errno
自变量被忽略。在其它平台,
winerror
自变量被忽略,和
winerror
属性不存在。
strerror
¶
相应的错误消息,由操作系统提供。它被格式化由 C 函数
perror()
在 POSIX (便携式操作系统接口),和
FormatMessage()
在 Windows。
filename
¶
filename2
¶
对于涉及文件系统路径的异常 (譬如
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 版改变:
The
filename
属性现在是传递给函数的原始文件名,而不是编码到或解码自文件系统编码的名称。另外,
filename2
构造函数自变量和属性的添加。
OverflowError
¶
被引发当算术运算的结果太大不能表示时。这不会发生对于整数 (其宁愿引发
MemoryError
而不是放弃)。不管怎样,由于历史原因,有时会为超出要求范围的整数引发 OverflowError。因为 C 缺乏浮点异常处理的标准化,所以大多数浮点运算都不校验。
RecursionError
¶
此异常派生自
RuntimeError
。它被引发当解释器检测到最大递归深度 (见
sys.getrecursionlimit()
) 超过。
3.5 版新增:
先前,纯
RuntimeError
被引发。
ReferenceError
¶
此异常被引发当弱引用代理时,创建通过
weakref.proxy()
函数,用于访问所指属性在它被垃圾收集之后。有关弱引用的更多信息,见
weakref
模块。
RuntimeError
¶
被引发当检测到不属于任何其它类别的错误时。关联值是指示哪里准确出错的字符串。
StopIteration
¶
被引发通过内置函数
next()
和
iterator
‘s
__next__()
方法以发出迭代器没有进一步项产生的信号。
异常对象拥有单属性
value
,其作为自变量给出当构造异常时,且默认为
None
.
当
generator
or
协程
函数返回,新的
StopIteration
实例被引发,并将由函数返回的值用作
value
参数用于异常构造函数。
If a generator function defined in the presence of a
from __future__
import generator_stop
directive raises
StopIteration
, it will be converted into a
RuntimeError
(保留
StopIteration
作为新异常的原因)。
3.3 版改变:
添加
value
属性和生成器函数能力以使用它来返回值。
3.5 版改变: Introduced the RuntimeError transformation.
StopAsyncIteration
¶
必须被引发通过
__anext__()
方法对于
异步迭代器
对象以停止迭代。
3.5 版新增。
SyntaxError
¶
被引发当剖析器遇到句法错误时。这可能发生在
import
语句,在调用内置函数
exec()
or
eval()
,或当读取初始脚本或标准输入 (也交互) 时。
Instances of this class have attributes
filename
,
lineno
,
offset
and
text
for easier access to the details.
str()
of the exception instance returns only the message.
IndentationError
¶
不正确缩进相关句法错误的基类。这是子类化的
SyntaxError
.
TabError
¶
Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of
IndentationError
.
SystemError
¶
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.
SystemExit
¶
此异常被引发通过
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()
).
code
¶
传递给构造函数的退出状态或错误消息。(默认为
None
)。
TypeError
¶
被引发当操作 (或函数) 被应用于不适当类型的对象时。关联值是字符串,给出类型不匹配的有关细节。
UnboundLocalError
¶
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
.
UnicodeError
¶
被引发当发生 Unicode 相关编码或解码错误时。它是子类化的
ValueError
.
UnicodeError
拥有描述编码 (或解码) 错误的属性。例如,
err.object[err.start:err.end]
gives the particular invalid input that the codec failed on.
encoding
¶
引发错误的编码名称。
reason
¶
描述特定编解码器错误的字符串。
object
¶
试图编码 (或解码) 的编解码器对象。
UnicodeEncodeError
¶
Raised when a Unicode-related error occurs during encoding. It is a subclass of
UnicodeError
.
UnicodeDecodeError
¶
Raised when a Unicode-related error occurs during decoding. It is a subclass of
UnicodeError
.
UnicodeTranslateError
¶
Raised when a Unicode-related error occurs during translating. It is a subclass of
UnicodeError
.
ValueError
¶
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as
IndexError
.
ZeroDivisionError
¶
被引发当除法 (或模) 运算的第 2 自变量为 0。关联值是指示操作数和运算类型的字符串。
保留下列异常是为兼容先前版本;从 Python 3.3 开始,它们是别名化的
OSError
.
EnvironmentError
¶
IOError
¶
WindowsError
¶
只可用于 Windows。
以下异常是子类化的
OSError
,它们根据系统错误代码引发。
BlockingIOError
¶
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
可以拥有更多属性:
ChildProcessError
¶
被引发当操作子级进程失败时。相当于
errno
ECHILD
.
ConnectionError
¶
连接相关问题的基类。
子类
BrokenPipeError
,
ConnectionAbortedError
,
ConnectionRefusedError
and
ConnectionResetError
.
BrokenPipeError
¶
子类化的
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
.
ConnectionAbortedError
¶
子类化的
ConnectionError
,被引发当对等方中止连接尝试时。相当于
errno
ECONNABORTED
.
ConnectionRefusedError
¶
子类化的
ConnectionError
, raised when a connection attempt is refused by the peer. Corresponds to
errno
ECONNREFUSED
.
ConnectionResetError
¶
子类化的
ConnectionError
, raised when a connection is reset by the peer. Corresponds to
errno
ECONNRESET
.
FileExistsError
¶
Raised when trying to create a file or directory which already exists. Corresponds to
errno
EEXIST
.
FileNotFoundError
¶
Raised when a file or directory is requested but doesn’t exist. Corresponds to
errno
ENOENT
.
InterruptedError
¶
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
.
IsADirectoryError
¶
被引发当文件操作 (譬如
os.remove()
) 请求目录。相当于
errno
EISDIR
.
NotADirectoryError
¶
被引发当目录操作 (譬如
os.listdir()
) is requested on something which is not a directory. Corresponds to
errno
ENOTDIR
.
PermissionError
¶
Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to
errno
EACCES
and
EPERM
.
ProcessLookupError
¶
被引发当给定进程不存在。相当于
errno
ESRCH
.
TimeoutError
¶
被引发当系统函数在系统级超时时。相当于
errno
ETIMEDOUT
.
3.3 版新增:
所有以上
OSError
子类被添加。
另请参阅
PEP 3151 - 返工 OS 和 IO 异常层次结构
下列异常被用作警告类别;见
warnings
module for more information.
警告
¶
警告类别的基类。
UserWarning
¶
由用户代码生成的警告的基类。
DeprecationWarning
¶
Base class for warnings about deprecated features.
PendingDeprecationWarning
¶
Base class for warnings about features which will be deprecated in the future.
SyntaxWarning
¶
Base class for warnings about dubious syntax.
RuntimeWarning
¶
Base class for warnings about dubious runtime behavior.
FutureWarning
¶
Base class for warnings about constructs that will change semantically in the future.
ImportWarning
¶
Base class for warnings about probable mistakes in module imports.
UnicodeWarning
¶
Base class for warnings related to Unicode.
ResourceWarning
¶
用于资源使用情况的相关警告基类。
3.2 版新增。
内置异常的类层次结构:
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError +-- 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 +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning