8. 错误和异常 Errors and Exceptions

Until now error messages haven't been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.

至今为止还没有进一步的谈论过错误信息,不过在你已经试验过的那些例子中,可能已经遇到过一些。Python 中(至少)有两种错误:语法错误和异常( syntax errorsand exceptions )。

section语法错误 Syntax Errors

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:

语法错误,也称作解析错误,可能是学习 Python 的过程中最容易犯的:

>>> while True print 'Hello world'
  File "<stdin>", line 1, in ?
    while True print 'Hello world'
SyntaxError: invalid syntax

The parser repeats the offending line and displays a little `arrow' pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the keyword print, since a colon (":") is missing before it. File name and line number are printed so you know where to look in case the input came from a script.

解析器会重复出错的行,并在行中最早发现的错误位置上显示一个小箭头。错误(至少是被检测到的)就发生在箭头指向的位置。示例中的错误表现在关键字print 上,因为在它之前少了一个冒号( ":")。同时也会显示文件名和行号,这样你就可以知道错误来自哪个脚本,什么位置。

8.1 异常 Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:

即使是在语法上完全正确的语句,尝试执行它的时候,也有可能会发生错误。在程序运行中检测出的错误称之为异常,它通常不会导致致命的问题,你很快就会学到如何在 Python 程序中控制它们。大多数异常不会由程序处理,而是显示一个错误信息:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects

The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError. The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).

错误信息的最后一行指出发生了什么错误。异常也有不同的类型,异常类型做为错误信息的一部分显示出来:示例中的异常分别为 零除错误( ZeroDivisionError )命名错误( NameError)类型错误(TypeError)。打印错误信息时,异常的类型作为异常的内置名显示。对于所有的内置异常都是如此,不过用户自定义异常就不一定了(尽管这是一个很有用的约定)。标准异常名是内置的标识(没有保留关键字)。

The rest of the line is a detail whose interpretation depends on the exception type; its meaning is dependent on the exception type.


The preceding part of the error message shows the context where the exception happened, in the form of a stack backtrace. In general it contains a stack backtrace listing source lines; however, it will not display lines read from standard input.


The Python Library Reference lists the built-in exceptions and their meanings.

Python 库参考手册列出了内置异常和它们的含义。

8.2 处理异常 Handling Exceptions

It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

通过编程可以处理指定的异常。以下的例子重复要求用户输入一个值,直到用户输入的是一个合法的整数为止。不过这个程序允许用户中断程序(使用Control-C 或者其它操作系统支持的方法)。需要注意的是用户发出的中断会引发一个KeyboardInterrupt 异常。

>>> while True:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops! That was no valid number.  Try again..."

The try statement works as follows.

try 语句按如下方式工作:

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized list, for example:

一个 try 语句可能包含多个 except 子句,分别指定处理不同的异常。至多只会有一个分支被执行。异常处理程序只会处理对应的 try 子句中发生的异常,在同一个 try 语句中,其他子句中发生的异常则不作处理。一个except子句可以在括号中列出多个异常的名字,例如:

... except (RuntimeError, TypeError, NameError):
...     pass

The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way! It can also be used to print an error message and then re-raise the exception (allowing a caller to handle the exception as well):

最后一个 except 子句可以省略异常名,把它当做一个通配项使用。一定要慎用这种方法,因为它很可能会屏蔽掉真正的程序错误,使人无法发现!它也可以用于打印一行错误信息,然后重新抛出异常(可以使调用者更好的处理异常)。

import sys

    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError, (errno, strerror):
    print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
    print "Unexpected error:", sys.exc_info()[0]

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:

try ... except 语句可以带有一个 else 子句, 该子句只能出现在所有 except 子句之后。当 try 语句没有抛出异常时,需要执行一些代码,可以使用这个子句。例如:

for arg in sys.argv[1:]:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
        print arg, 'has', len(f.readlines()), 'lines'

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn't raised by the code being protected by the try ... except statement.

使用 else 子句比在 try 子句中附加代码要好,因为这样可以避免 try ...
keywordexcept 意外的截获本来不属于它们保护的那些代码抛出的异常。

When an exception occurs, it may have an associated value, also known as the exception's argument. The presence and type of the argument depend on the exception type.


The except clause may specify a variable after the exception name (or list). The variable is bound to an exception instance with the arguments stored in instance.args. For convenience, the exception instance defines __getitem__ and __str__ so the arguments can be accessed or printed directly without having to reference .args.

在异常名(列表)之后,也可以为 except 子句指定一个变量。这个变量绑定于一个异常实例,它存储在 instance.args 的参数中。为了方便起见,异常实例定义了 __getitem____str__,这样就可以直接访问过打印参数而不必引用 .args

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception, inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
<type 'instance'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

If an exception has an argument, it is printed as the last part (`detail') of the message for unhandled exceptions.


Exception handlers don't just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For example:

异常处理句柄不止可以处理直接发生在 try 子句中的异常,即使是其中(甚至是间接)调用的函数,发生了异常,也一样可以处理。例如:

>>> def this_fails():
...     x = 1/0
>>> try:
...     this_fails()
... except ZeroDivisionError, detail:
...     print 'Handling run-time error:', detail
Handling run-time error: integer division or modulo

8.3 抛出异常 Raising Exceptions

The raise statement allows the programmer to force a specified exception to occur. For example:

在发生了特定的异常时,程序员可以用 raise 语句强制抛出异常。例如:

>>> raise NameError, 'HiThere'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: HiThere

The first argument to raise names the exception to be raised. The optional second argument specifies the exception's argument.


If you need to determine whether an exception was raised but don't intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:

如果你决定抛出一个异常而不处理它, raise 语句可以让你很简单的重新抛出该异常。

>>> try:
...     raise NameError, 'HiThere'
... except NameError:
...     print 'An exception flew by!'
...     raise
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: HiThere

8.4 用户自定义异常 User-defined Exceptions

Programs may name their own exceptions by creating a new exception class. Exceptions should typically be derived from the Exception class, either directly or indirectly. For example:

在程序中可以通过创建新的异常类型来命名自己的异常。异常类通常应该直接或间接的从 Exception 类派生,例如:

>>> class MyError(Exception):
...     def __init__(self, value):
...         self.value = value
...     def __str__(self):
...         return repr(self.value)
>>> try:
...     raise MyError(2*2)
... except MyError, e:
...     print 'My exception occurred, value:', e.value
My exception occurred, value: 4
>>> raise MyError, 'oops!'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception. When creating a module which can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:


class Error(Exception):
    """Base class for exceptions in this module."""

class InputError(Error):
    """Exception raised for errors in the input.

        expression -- input expression in which the error occurred
        message -- explanation of the error

    def __init__(self, expression, message):
        self.expression = expression
        self.message = message

class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not

        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed

    def __init__(self, previous, next, message):
        self.previous = previous = next
        self.message = message

Most exceptions are defined with names that end in ``Error,'' similar to the naming of the standard exceptions.


Many standard modules define their own exceptions to report errors that may occur in functions they define. More information on classes is presented in chapter , ``Classes.''

很多标准模块中都定义了自己的异常,用以报告在他们所定义的函数中可能发生的错误。关于类的进一步信息请参见第 9 章 ,“类”。

8.5 定义清理行为 Defining Clean-up Actions

The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:

try 语句还有另一个可选的子句,目的在于定义在任何情况下都一定要执行的功能。例如:

>>> try:
...     raise KeyboardInterrupt
... finally:
...     print 'Goodbye, world!'
Goodbye, world!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?

A finally clause is executed whether or not an exception has occurred in the try clause. When an exception has occurred, it is re-raised after the finally clause is executed. The finally clause is also executed ``on the way out'' when the try statement is left via a break or return statement.

不管try子句中有没有发生异常, finally 子句都一定会被执行。如果发生异常,在 finally 子句执行完后它会被重新抛出。 try 子句经由 breakreturn 退出也一样会执行 finally 子句。

The code in the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether or not the use of the resource was successful.

在 finally 子句中的代码用于释放外部资源(例如文件或网络连接),不管这些资源是否已经成功利用。

A try statement must either have one or more except clauses or one finally clause, but not both.

try 语句中可以使用若干个 except 子句或一个 finally 子句,但两者不能共存。

译者:刘鑫(march.liu AT gmail DOT com) 由:limodou转(limodou AT gmail DOT com)
See About this document... for information on suggesting changes.