6. 内置异常¶
Exceptions should be class objects. The exceptions are defined in the module
exceptions
. This module never needs to be imported explicitly: the
exceptions are provided in the built-in namespace as well as the
exceptions
module.
For class exceptions, in a try
statement with an 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
containing several items of information (e.g., an error code and a string
explaining the code). The associated value is the second argument to the
raise
statement. If the exception class is derived from the standard
root class BaseException
, the associated value is present as the
exception instance’s args
attribute.
用户代码可以引发内置异常。 这可被用于测试异常处理程序或报告错误条件,“就像” 在解释器引发了相同异常的情况时一样;但是请注意,没有任何机制能防止用户代码引发不适当的错误。
内置异常类可以被子类化以定义新的异常;鼓励程序员从 Exception
类或它的某个子类而不是从 BaseException
来派生新的异常。 关于定义异常的更多信息可以在 Python 教程的 用户自定义异常 部分查看。
The following exceptions are only used as base classes for other exceptions.
-
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
). Ifstr()
orunicode()
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.2.5 新版功能.
-
exception
Exception
¶ 所有内置的非系统退出类异常都派生自此类。 所有用户自定义异常也应当派生自此类。
在 2.5 版更改: Changed to inherit from
BaseException
.
-
exception
StandardError
¶ The base class for all built-in exceptions except
StopIteration
,GeneratorExit
,KeyboardInterrupt
andSystemExit
.StandardError
itself is derived fromException
.
-
exception
ArithmeticError
¶ 此基类用于派生针对各种算术类错误而引发的内置异常:
OverflowError
,ZeroDivisionError
,FloatingPointError
。
-
exception
LookupError
¶ 此基类用于派生当映射或序列所使用的键或索引无效时引发的异常:
IndexError
,KeyError
。 这可以通过codecs.lookup()
来直接引发。
-
exception
EnvironmentError
¶ The base class for exceptions that can occur outside the Python system:
IOError
,OSError
. When exceptions of this type are created with a 2-tuple, the first item is available on the instance’serrno
attribute (it is assumed to be an error number), and the second item is available on thestrerror
attribute (it is usually the associated error message). The tuple itself is also available on theargs
attribute.1.5.2 新版功能.
When an
EnvironmentError
exception is instantiated with a 3-tuple, the first two items are available as above, while the third item is available on thefilename
attribute. However, for backwards compatibility, theargs
attribute contains only a 2-tuple of the first two constructor arguments.The
filename
attribute isNone
when this exception is created with other than 3 arguments. Theerrno
andstrerror
attributes are alsoNone
when the instance was created with other than 2 or 3 arguments. In this last case,args
contains the verbatim constructor arguments as a tuple.
The following exceptions are the exceptions that are actually raised.
-
exception
EOFError
¶ Raised when one of the built-in functions (
input()
orraw_input()
) hits an end-of-file condition (EOF) without reading any data. (N.B.: thefile.read()
andfile.readline()
methods return an empty string when they hit EOF.)
-
exception
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 theWANT_SIGFPE_HANDLER
symbol is defined in thepyconfig.h
file.
-
exception
GeneratorExit
¶ Raised when a generator’s
close()
method is called. It directly inherits fromBaseException
instead ofStandardError
since it is technically not an error.2.5 新版功能.
在 2.6 版更改: Changed to inherit from
BaseException
.
-
exception
IOError
¶ Raised when an I/O operation (such as a
print
statement, the built-inopen()
function or a method of a file object) fails for an I/O-related reason, e.g., “file not found” or “disk full”.This class is derived from
EnvironmentError
. See the discussion above for more information on exception instance attributes.在 2.6 版更改: Changed
socket.error
to use this as a base class.
-
exception
ImportError
¶ Raised when an
import
statement fails to find the module definition or when afrom ... import
fails to find a name that is to be imported.
-
exception
IndexError
¶ Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not a plain integer,
TypeError
is raised.)
-
exception
KeyError
¶ 当在现有键集合中找不到指定的映射(字典)键时将被引发。
-
exception
KeyboardInterrupt
¶ Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly. Interrupts typed when a built-in function
input()
orraw_input()
is waiting for input also raise this exception. The exception inherits fromBaseException
so as to not be accidentally caught by code that catchesException
and thus prevent the interpreter from exiting.在 2.5 版更改: Changed to inherit from
BaseException
.
-
exception
MemoryError
¶ 当一个操作耗尽内存但情况仍可(通过删除一些对象)进行挽救时将被引发。 关联的值是一个字符串,指明是哪种(内部)操作耗尽了内存。 请注意由于底层的内存管理架构(C 的
malloc()
函数),解释器也许并不总是能够从这种情况下完全恢复;但它毕竟可以引发一个异常,这样就能打印出栈回溯信息,以便找出导致问题的失控程序。
-
exception
NameError
¶ 当某个局部或全局名称未找到时将被引发。 此异常仅用于非限定名称。 关联的值是一条错误信息,其中包含未找到的名称。
-
exception
NotImplementedError
¶ This exception is derived from
RuntimeError
. In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method.1.5.2 新版功能.
-
exception
OSError
¶ This exception is derived from
EnvironmentError
. It is raised when a function returns a system-related error (not for illegal argument types or other incidental errors). Theerrno
attribute is a numeric error code fromerrno
, and thestrerror
attribute is the corresponding string, as would be printed by the C functionperror()
. See the moduleerrno
, which contains names for the error codes defined by the underlying operating system.For exceptions that involve a file system path (such as
chdir()
orunlink()
), the exception instance will contain a third attribute,filename
, which is the file name passed to the function.1.5.2 新版功能.
-
exception
OverflowError
¶ Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for long integers (which would rather raise
MemoryError
than give up) and for most operations with plain integers, which return a long integer instead. Because of the lack of standardization of floating point exception handling in C, most floating point operations also aren’t checked.
-
exception
ReferenceError
¶ 此异常将在使用
weakref.proxy()
函数所创建的弱引用来访问该引用的某个已被作为垃圾回收的属性时被引发。 有关弱引用的更多信息请参阅weakref
模块。2.2 新版功能: Previously known as the
weakref.ReferenceError
exception.
-
exception
RuntimeError
¶ 当检测到一个不归属于任何其他类别的错误时将被引发。 关联的值是一个指明究竟发生了什么问题的字符串。
-
exception
StopIteration
¶ Raised by an iterator’s
next()
method to signal that there are no further values. This is derived fromException
rather thanStandardError
, since this is not considered an error in its normal application.2.2 新版功能.
-
exception
SyntaxError
¶ Raised when the parser encounters a syntax error. This may occur in an
import
statement, in anexec
statement, in a call to the built-in functioneval()
orinput()
, or when reading the initial script or standard input (also interactively).该类的实例包含有属性
filename
,lineno
,offset
和text
用于方便地访问相应的详细信息。 异常实例的str()
仅返回消息文本。
-
exception
IndentationError
¶ 与不正确的缩进相关的语法错误的基类。 这是
SyntaxError
的一个子类。
-
exception
TabError
¶ 当缩进包含对制表符和空格符不一致的使用时将被引发。 这是
IndentationError
的一个子类。
-
exception
SystemError
¶ 当解释器发现内部错误,但情况看起来尚未严重到要放弃所有希望时将被引发。 关联的值是一个指明发生了什么问题的字符串(表示为低层级的符号)。
你应当将此问题报告给你所用 Python 解释器的作者或维护人员。 请确认报告 Python 解释器的版本号 (
sys.version
; 它也会在交互式 Python 会话开始时被打印出来),具体的错误消息(异常所关联的值)以及可能触发该错误的程序源码。
-
exception
SystemExit
¶ This exception is raised by the
sys.exit()
function. When it is not handled, the Python interpreter exits; no stack traceback is printed. If the associated value is a plain integer, it specifies the system exit status (passed to C’sexit()
function); if it isNone
, 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.Instances have an attribute
code
which is set to the proposed exit status or error message (defaulting toNone
). Also, this exception derives directly fromBaseException
and notStandardError
, since it is not technically an error.对
sys.exit()
的调用会被转换为一个异常以便能执行清理处理程序 (try
语句的finally
子句),并且使得调试器可以执行一段脚本而不必冒失去控制的风险。 如果绝对确实地需要立即退出(例如在调用os.fork()
之后的子进程中)则可使用os._exit()
.The exception inherits from
BaseException
instead ofStandardError
orException
so that it is not accidentally caught by code that catchesException
. This allows the exception to properly propagate up and cause the interpreter to exit.在 2.5 版更改: Changed to inherit from
BaseException
.
-
exception
TypeError
¶ 当一个操作或函数被应用于类型不适当的对象时将被引发。 关联的值是一个字符串,给出有关类型不匹配的详情。
-
exception
UnicodeError
¶ 当发生与 Unicode 相关的编码或解码错误时将被引发。 此异常是
ValueError
的一个子类。UnicodeError
具有一些描述编码或解码错误的属性。 例如err.object[err.start:err.end]
会给出导致编解码器失败的特定无效输入。-
encoding
¶ 引发错误的编码名称。
-
reason
¶ 描述特定编解码器错误的字符串。
-
object
¶ 编解码器试图要编码或解码的对象。
2.0 新版功能.
-
-
exception
UnicodeEncodeError
¶ 当在编码过程中发生与 Unicode 相关的错误时将被引发。 此异常是
UnicodeError
的一个子类。2.3 新版功能.
-
exception
UnicodeDecodeError
¶ 当在解码过程中发生与 Unicode 相关的错误时将被引发。 此异常是
UnicodeError
的一个子类。2.3 新版功能.
-
exception
UnicodeTranslateError
¶ 在转写过程中发生与 Unicode 相关的错误时将被引发。 此异常是
UnicodeError
的一个子类。2.3 新版功能.
-
exception
ValueError
¶ 当操作或函数接收到具有正确类型但值不适合的参数,并且情况不能用更精确的异常例如
IndexError
来描述时将被引发。
-
exception
VMSError
¶ Only available on VMS. Raised when a VMS-specific error occurs.
-
exception
WindowsError
¶ Raised when a Windows-specific error occurs or when the error number does not correspond to an
errno
value. Thewinerror
andstrerror
values are created from the return values of theGetLastError()
andFormatMessage()
functions from the Windows Platform API. Theerrno
value maps thewinerror
value to correspondingerrno.h
values. This is a subclass ofOSError
.2.0 新版功能.
在 2.5 版更改: Previous versions put the
GetLastError()
codes intoerrno
.
-
exception
ZeroDivisionError
¶ 当除法或取余运算的第二个参数为零时将被引发。 关联的值是一个字符串,指明操作数和运算的类型。
The following exceptions are used as warning categories; see the warnings
module for more information.
-
exception
Warning
¶ 警告类别的基类。
-
exception
UserWarning
¶ 用户代码所产生警告的基类。
-
exception
DeprecationWarning
¶ Base class for warnings about deprecated features.
-
exception
PendingDeprecationWarning
¶ Base class for warnings about features which will be deprecated in the future.
-
exception
SyntaxWarning
¶ 与模糊的语法相关的警告的基类。
-
exception
RuntimeWarning
¶ 与模糊的运行时行为相关的警告的基类。
-
exception
FutureWarning
¶ Base class for warnings about constructs that will change semantically in the future.
-
exception
ImportWarning
¶ 与在模块导入中可能的错误相关的警告的基类。
2.5 新版功能.
-
exception
UnicodeWarning
¶ 与 Unicode 相关的警告的基类。
2.5 新版功能.
-
exception
BytesWarning
¶ Base class for warnings related to bytes and bytearray.
2.6 新版功能.
6.1. 异常层次结构¶
内置异常的类层级结构如下:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning