# 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`). If `str()` or `unicode()` 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 新版功能.

  `args`

    The tuple of arguments given to the exception constructor. Some built-in exceptions (like `IOError`) 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.

exception `Exception`

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

  在 2.5 版更改: Changed to inherit from `BaseException`.

exception `StandardError`

  The base class for all built-in exceptions except `StopIteration`, `GeneratorExit`, `KeyboardInterrupt` and `SystemExit`. `StandardError` itself is derived from `Exception`.

exception `ArithmeticError`

  此基类用于派生针对各种算术类错误而引发的内置异常: `OverflowError`, `ZeroDivisionError`, `FloatingPointError`。

exception `BufferError`

  当与 缓冲区 相关的操作无法执行时将被引发。

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’s `errno` attribute (it is assumed to be an error number), and the second item is available on the `strerror` attribute (it is usually the associated error message). The tuple itself is also available on the `args` 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 the `filename` attribute. However, for backwards compatibility, the `args` attribute contains only a 2-tuple of the first two constructor arguments.

  The `filename` attribute is `None` when this exception is created with other than 3 arguments. The `errno` and `strerror` attributes are also `None` 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 `AssertionError`

  当 `assert` 语句失败时将被引发。

exception `AttributeError`

  当属性引用 (参见 属性引用) 或赋值失败时将被引发。 （当一个对象根本不支持属性引用或属性赋值时则将引发 `TypeError`。）

exception `EOFError`

  Raised when one of the built-in functions (`input()` or `raw_input()`) hits an end-of-file condition (EOF) without reading any data. (N.B.: the `file.read()` and `file.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 the `WANT_SIGFPE_HANDLER` symbol is defined in the `pyconfig.h` file.

exception `GeneratorExit`

  Raised when a generator’s `close()` method is called. It directly inherits from `BaseException` instead of `StandardError` 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-in `open()` 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 a `from ... 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()` or `raw_input()` is waiting for input also raise this exception. The exception inherits from `BaseException` so as to not be accidentally caught by code that catches `Exception` 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). The `errno` attribute is a numeric error code from `errno`, and the `strerror` attribute is the corresponding string, as would be printed by the C function `perror()`. See the module `errno`, which contains names for the error codes defined by the underlying operating system.

  For exceptions that involve a file system path (such as `chdir()` or `unlink()`), 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 from `Exception` rather than `StandardError`, 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 an `exec` statement, in a call to the built-in function `eval()` or `input()`, 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’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.

  Instances have an attribute `code` which is set to the proposed exit status or error message (defaulting to `None`). Also, this exception derives directly from `BaseException` and not `StandardError`, since it is not technically an error.

  对 `sys.exit()` 的调用会被转换为一个异常以便能执行清理处理程序 (`try` 语句的 `finally` 子句)，并且使得调试器可以执行一段脚本而不必冒失去控制的风险。 如果绝对确实地需要立即退出（例如在调用 `os.fork()` 之后的子进程中）则可使用 `os._exit()`.

  The exception inherits from `BaseException` instead of `StandardError` or `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.

  在 2.5 版更改: Changed to inherit from `BaseException`.

exception `TypeError`

  当一个操作或函数被应用于类型不适当的对象时将被引发。 关联的值是一个字符串，给出有关类型不匹配的详情。

exception `UnboundLocalError`

  当在函数或方法中对某个局部变量进行引用，但该变量并未绑定任何值时将被引发。 此异常是 `NameError` 的一个子类。

  2.0 新版功能.

exception `UnicodeError`

  当发生与 Unicode 相关的编码或解码错误时将被引发。 此异常是 `ValueError` 的一个子类。

  `UnicodeError` 具有一些描述编码或解码错误的属性。 例如 `err.object[err.start:err.end]` 会给出导致编解码器失败的特定无效输入。

  `encoding`

    引发错误的编码名称。

  `reason`

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

  `object`

    编解码器试图要编码或解码的对象。

  `start`

    `object` 中无效数据的开始位置索引。

  `end`

    `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. The `winerror` and `strerror` values are created from the return values of the `GetLastError()` and `FormatMessage()` functions from the Windows Platform API. The `errno` value maps the `winerror` value to corresponding `errno.h` values. This is a subclass of `OSError`.

  2.0 新版功能.

  在 2.5 版更改: Previous versions put the `GetLastError()` codes into `errno`.

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