4.2 异常 Exceptions

Exceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. An exception is raisedat the point where the error is detected; it may be handledby the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred.

异常就是为了处理出错或者处理其它意外情况而中断代码块的正常控制流。异常在错误被检测到的位置被抛出.它可以被其周围相关代码的处理, 或者错误发生处直接或间接调用的代码块处理.

The Python interpreter raises an exception when it detects a run-time error (such as division by zero). A Python program can also explicitly raise an exception with the raise statement. Exception handlers are specified with the try ... except statement. The try ... finally statement specifies cleanup code which does not handle the exception, but is executed whether an exception occurred or not in the preceding code.

Python解释器在它检测到一个运行时错误时抛出一个异常(比如除法零).某个Python 程序也可以通过raise语句显式地抛出异常.异常处理器可以用 try ... except语句指定. try ... finally语句指定清理代码块,但是它不处理异常,只是无论先前代码中是否产生异常都会得到执行。

Python uses the ``termination''model of error handling: an exception handler can find out what happened and continue execution at an outer level, but it cannot repair the cause of the error and retry the failing operation (except by re-entering the offending piece of code from the top).

Python使用所谓的"中断"错误处理模型:一个异常处理器能在外层找出错误发生和继续执行的位置. 但是它不能修复错误和重试错误的操作(除非重新从头进入该段出错的代码).

When an exception is not handled at all, the interpreter terminates execution of the program, or returns to its interactive main loop. In either case, it prints a stack backtrace, except when the exception is SystemExit.

当一个异常没有得到控制, 解释器就中断程序的执行, 或返回到它的主循环的迭代中. 其它情况下, 除了不是SystemExit异常, 它还打印一个堆栈跟踪回溯对象.

Exceptions are identified by class instances. Selection of a matching except clause is based on object identity. The except clause must reference the same class or a base class of it.

异常由一个字符串对象或一个类实例标识.所匹配的except子句的选择是基于对象标识的. (也就是说, 两个具有相同值的字符串对象描述的是不同的对象)对于字符串对象, except子句必须引用相同的串对象, 对于类异常, except子句必须引用相同的类或其基类.

When an exception is raised, an object (maybe None) is passed as the exception's value; this object does not affect the selection of an exception handler, but is passed to the selected exception handler as additional information. For class exceptions, this object must be an instance of the exception class being raised.

当一个异常被抛出时, 某个对象(可能是None)会作为异常的参数或值被传给异常处理器; 这个对象不影响异常处理器的选择, 但会传递给异常处理器以提供扩展信息.对于类异常, 这个对象必须是被抛出的异常类的实例.

Warning: Messages to exceptions are not part of the Python API. Their contents may change from one version of Python to the next without warning and should not be relied on by code which will run under multiple versions of the interpreter.

See also the description of the try statement in section 7.4 and raise statement in section 6.9.

关于try语句详见7.4; 关于raise语句详见6.9