内置异常

在 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.

基类

以下异常主要用作其它异常的基类。

exception 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 Exception

所有内置、非系统退出异常都派生自此类。所有用户定义异常也应派生自此类。

exception ArithmeticError

The base class for those built-in exceptions that are raised for various arithmetic errors: OverflowError , ZeroDivisionError , FloatingPointError .

exception BufferError

被引发当 buffer 相关操作无法履行。

exception 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() .

具体异常

以下异常是通常引发的异常。

exception AssertionError

被引发当 assert 语句失败。

exception AttributeError

被引发当属性引用 (见 属性引用 ) 或赋值失败。(当对象根本不支持属性引用或属性赋值时, TypeError 被引发)。

exception 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.)

exception FloatingPointError

目前不使用。

exception GeneratorExit

被引发当 generator or 协程 被关闭;见 generator.close() and coroutine.close() 。它直接继承自 BaseException 而不是 Exception 由于它在技术上不是错误。

exception ImportError

被引发当 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.

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 属性。

exception ModuleNotFoundError

子类化的 ImportError 其被引发通过 import 当定位不到模块时。它也被引发当 None 发现于 sys.modules .

3.6 版新增。

exception IndexError

被引发当序列下标超出范围时。(会默默截断切片索引以落在允许范围内;若索引不是整数, TypeError 被引发)。

exception KeyError

被引发当在现有键集中找不到映射 (字典) 键时。

exception KeyboardInterrupt

被引发当用户命中中断键时 (通常 Control-C or 删除 )。在执行期间,会定期检查中断。异常继承自 BaseException 以免被意外捕获通过代码捕获 Exception 从而防止解释器退出。

exception MemoryError

被引发当操作耗尽内存但情况仍可以挽救 (通过删除一些对象)。关联值是指示哪种 (内部) 操作耗尽内存的字符串。注意,由于底层内存管理体系结构(C 的 malloc() 函数),解释器可能并不会总是能够从这种情况完全恢复;尽管如此,它会引发异常,以便在程序失控的情况下打印堆栈回溯。

exception NameError

被引发当找不到局部 (或全局) 名称时。这仅适用于不合格名称。关联值是包括找不到名称的错误消息。

exception NotImplementedError

此异常派生自 RuntimeError 。在用户定义的基类中,抽象方法应引发此异常当它们要求派生类覆盖方法时,或者当在开发类指示仍然需要添加真正实现时。

注意

它不应该被用于指示意味着根本不支持的运算符 (或方法) – 在这种情况下,要么不定义运算符 (或方法),要么若是子类,则将它设为 None .

注意

NotImplementedError and NotImplemented 不可互换,即使它们拥有相似的名称和用途。见 NotImplemented 了解使用时的有关细节。

exception OSError ( [ arg ] )
exception 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 构造函数自变量和属性的添加。

exception OverflowError

被引发当算术运算的结果太大不能表示时。这不会发生对于整数 (其宁愿引发 MemoryError 而不是放弃)。不管怎样,由于历史原因,有时会为超出要求范围的整数引发 OverflowError。因为 C 缺乏浮点异常处理的标准化,所以大多数浮点运算都不校验。

exception RecursionError

此异常派生自 RuntimeError 。它被引发当解释器检测到最大递归深度 (见 sys.getrecursionlimit() ) 超过。

3.5 版新增: 先前,纯 RuntimeError 被引发。

exception ReferenceError

此异常被引发当弱引用代理时,创建通过 weakref.proxy() 函数,用于访问所指属性在它被垃圾收集之后。有关弱引用的更多信息,见 weakref 模块。

exception RuntimeError

被引发当检测到不属于任何其它类别的错误时。关联值是指示哪里准确出错的字符串。

exception StopIteration

被引发通过内置函数 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 .

exception StopAsyncIteration

必须被引发通过 __anext__() 方法对于 异步迭代器 对象以停止迭代。

3.5 版新增。

exception SyntaxError

被引发当剖析器遇到句法错误时。这可能发生在 import 语句,在调用内置函数 exec() or eval() ,或当读取初始脚本或标准输入 (也交互) 时。

The str() of the exception instance returns only the error message.

filename

发生句法错误的文件名。

lineno

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.

offset

The column in the line where the error occurred. This is 1-indexed: the first character in the line has an offset of 1.

text

错误中涉及的源代码文本。

exception IndentationError

不正确缩进相关句法错误的基类。这是子类化的 SyntaxError .

exception TabError

Raised when indentation contains an inconsistent use of tabs and spaces. This is a subclass of IndentationError .

exception 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.

exception 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 )。

exception TypeError

被引发当操作 (或函数) 被应用于不适当类型的对象时。关联值是字符串,给出类型不匹配的有关细节。

此异常可能由用户代码引发,以指示不支持且不意味着支持对象所尝试的操作。若对象意味着支持给定操作但尚未提供实现, 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 .

exception 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 .

exception UnicodeError

被引发当发生 Unicode 相关编码或解码错误时。它是子类化的 ValueError .

UnicodeError 拥有描述编码 (或解码) 错误的属性。例如, err.object[err.start:err.end] gives the particular invalid input that the codec failed on.

encoding

引发错误的编码名称。

reason

描述特定编解码器错误的字符串。

object

试图编码 (或解码) 的编解码器对象。

start

无效数据的第一索引在 object .

end

最后无效数据之后的索引在 object .

exception UnicodeEncodeError

Raised when a Unicode-related error occurs during encoding. It is a subclass of UnicodeError .

exception UnicodeDecodeError

Raised when a Unicode-related error occurs during decoding. It is a subclass of UnicodeError .

exception UnicodeTranslateError

Raised when a Unicode-related error occurs during translating. It is a subclass of UnicodeError .

exception ValueError

被引发当操作 (或函数) 收到类型正确但值不合适的自变量,且未按更准确异常描述这种情况,譬如 IndexError .

exception ZeroDivisionError

被引发当除法 (或模) 运算的第 2 自变量为 0。关联值是指示操作数和运算类型的字符串。

保留下列异常是为兼容先前版本;从 Python 3.3 开始,它们是别名化的 OSError .

exception EnvironmentError
exception IOError
exception WindowsError

只可用于 Windows。

OS 异常

以下异常是子类化的 OSError ,它们根据系统错误代码引发。

exception 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 可以拥有更多属性:

characters_written

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 模块。

exception ChildProcessError

被引发当操作子级进程失败时。相当于 errno ECHILD .

exception ConnectionError

连接相关问题的基类。

子类 BrokenPipeError , ConnectionAbortedError , ConnectionRefusedError and ConnectionResetError .

exception 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 .

exception ConnectionAbortedError

子类化的 ConnectionError ,被引发当对等方中止连接尝试时。相当于 errno ECONNABORTED .

exception ConnectionRefusedError

子类化的 ConnectionError , raised when a connection attempt is refused by the peer. Corresponds to errno ECONNREFUSED .

exception ConnectionResetError

子类化的 ConnectionError , raised when a connection is reset by the peer. Corresponds to errno ECONNRESET .

exception FileExistsError

Raised when trying to create a file or directory which already exists. Corresponds to errno EEXIST .

exception FileNotFoundError

Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT .

exception 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 .

exception IsADirectoryError

被引发当文件操作 (譬如 os.remove() ) 请求目录。相当于 errno EISDIR .

exception NotADirectoryError

被引发当目录操作 (譬如 os.listdir() ) is requested on something which is not a directory. Corresponds to errno ENOTDIR .

exception PermissionError

Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to errno EACCES and EPERM .

exception ProcessLookupError

被引发当给定进程不存在。相当于 errno ESRCH .

exception TimeoutError

被引发当系统函数在系统级超时时。相当于 errno ETIMEDOUT .

3.3 版新增: 所有以上 OSError 子类被添加。

另请参阅

PEP 3151 - 返工 OS 和 IO 异常层次结构

警告

下列异常被用作警告类别;见 警告类别 文档编制了解更多细节。

exception 警告

警告类别的基类。

exception UserWarning

由用户代码生成的警告的基类。

exception DeprecationWarning

Base class for warnings about deprecated features when those warnings are intended for other Python developers.

exception PendingDeprecationWarning

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.

exception SyntaxWarning

Base class for warnings about dubious syntax.

exception RuntimeWarning

Base class for warnings about dubious runtime behavior.

exception FutureWarning

Base class for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python.

exception ImportWarning

Base class for warnings about probable mistakes in module imports.

exception UnicodeWarning

Base class for warnings related to Unicode.

exception BytesWarning

Base class for warnings related to bytes and bytearray .

exception ResourceWarning

Base class for warnings related to resource usage. Ignored by the default warning filters.

3.2 版新增。

异常层次结构

内置异常的类层次结构:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- 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
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

内容表

上一话题

内置类型

下一话题

文本处理服务

本页