.. _tut-errors:
==================================
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 errors* and *exceptions* )。
.. _tut-syntaxerrors:
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 “”, 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 :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.
解析器会重复出错的行,并在行中最早发现的错误位置上显示一个小“箭头”。错误
(至少是被检测到的)就发生在箭头 *指向* 的位置。示例中的错误表现在关键字
:keyword:`print` 上,因为在它之前少了一个冒号( “’:’“ )。同时也会显示文件名和行号,
这样你就可以知道错误来自哪个脚本,什么位置。
.. _tut-exceptions:
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 “”, line 1, in ?
zeropisionerror: integer pision or modulo by zero
>>> 4 + spam*3
traceback (most recent call last):
file “”, line 1, in ?
nameerror: name ‘spam’ is not defined
>>> ‘2’ + 2
traceback (most recent call last):
file “”, 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 :exc:`zeropisionerror`, :exc:`nameerror` and :exc:`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).
错误信息的最后一行指出发生了什么错误。异常也有不同的类型,异常类型做为
错误信息的一部分显示出来:示例中的异常分别为 零除错误
( :exc:`zeropisionerror` ) ,命名错误( :exc:`nameerror`) 和 类型
错误(:exc:`typeerror` )。打印错误信息时,异常的类型作为异常的内置名
显示。对于所有的内置异常都是如此,不过用户自定义异常就不一定了(尽管这
是一个很有用的约定)。标准异常名是内置的标识(没有保留关键字)。
the rest of the line provides detail based on the type of exception and what
caused it.
这一行后一部分是关于该异常类型的详细说明,这意味着它的内容依赖于异常类型。
the preceding part of the error message shows the context where the exception
happened, in the form of a stack traceback. in general it contains a stack
traceback listing source lines; however, it will not display lines read from
standard input.
错误信息的前半部分以堆栈的形式列出异常发生的位置。通常在堆栈中列出了源代码行,然而,来自标准输入的源码不会显示出来。
:ref:`bltin-exceptions` lists the built-in exceptions and their meanings.
:ref:`bltin-exceptions` 列出了内置异常和它们的含义。
.. _tut-handling:
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 :kbd:`control-c` or
whatever the operating system supports); note that a user-generated interruption
is signalled by raising the :exc:`keyboardinterrupt` exception. :
可以编写程序来控制已知的异常。参见下例,此示例要求用户输入信息,一直到
得到一个有效的整数为止,而且允许用户中断程序(使用 :kbd:`control-c` 或
其它什么操作系统支持的操作);需要注意的是用户生成的中断会抛出
:exc:`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 :keyword:`try` statement works as follows.
:keyword:`try` 语句按如下方式工作。
* first, the *try clause* (the statement(s) between the :keyword:`try` and
:keyword:`except` keywords) is executed.
首先,执行 *try 子句* (在 :keyword:`try` 和 :keyword:`except` 关键字之间的部分)。
* if no exception occurs, the *except clause* is skipped and execution of the
:keyword:`try` statement is finished.
如果没有异常发生, *except 子句* 在 :keyword:`try` 语句执行完毕后就被忽略了。
* if an exception occurs during execution of the try clause, the rest of the
clause is skipped. then if its type matches the exception named after the
:keyword:`except` keyword, the except clause is executed, and then execution
continues after the :keyword:`try` statement.
如果在 try 子句执行过程中发生了异常,那么该子句其余的部分就会被忽略。
如果异常匹配于 :keyword:`except` 关键字后面指定的异常类型,就执行对应的except子
句。然后继续执行 :keyword:`try` 语句之后的代码。
* if an exception occurs which does not match the exception named in the except
clause, it is passed on to outer :keyword:`try` statements; if no handler is
found, it is an *unhandled exception* and execution stops with a message as
shown above.
如果发生了一个异常,在 except 子句中没有与之匹配的分支,它就会传递到
上一级 :keyword:`try` 语句中。如果最终仍找不到对应的处理语句,它就成
为一个 *未处理异常* ,终止程序运行,显示提示信息。
a :keyword:`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 :keyword:`try` statement. an except clause may
name multiple exceptions as a parenthesized tuple, for example:
一个 :keyword:`try` 语句可能包含多个 except 子句,分别指定处理不同的异
常。至多只会有一个分支被执行。异常处理程序只会处理对应的 try 子句中发
生的异常,在同一个 :keyword:`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
try:
f = open(‘myfile.txt’)
s = f.readline()
i = int(s.strip())
except ioerror as (errno, strerror):
print “i/o error({0}): {1}”.format(errno, strerror)
except valueerror:
print “could not convert data to an integer.”
except:
print “unexpected error:”, sys.exc_info()[0]
raise
the :keyword:`try` … :keyword:`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:
:keyword:`try` … :keyword:`except` 语句可以带有一个 *else 子句* ,
该子句只能出现在所有 except 子句之后。当 try 语句没有抛出异常时,需要执行一些代码,可以使用
这个子句。例如 ::
for arg in sys.argv[1:]:
try:
f = open(arg, ‘r’)
except ioerror:
print ‘cannot open’, arg
else:
print arg, ‘has’, len(f.readlines()), ‘lines’
f.close()
the use of the :keyword:`else` clause is better than adding additional code to
the :keyword:`try` clause because it avoids accidentally catching an exception
that wasn’t raised by the code being protected by the :keyword:`try` …
:keyword:`except` statement.
使用 :keyword:`else` 子句比在 :keyword:`try` 子句中附加代码要好,因为
这样可以避免 :keyword:`try` … :keyword:`except` 意外的截获本来不属于
它们保护的那些代码抛出的异常。
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 tuple).
the variable is bound to an exception instance with the arguments stored in
“instance.args“. for convenience, the exception instance defines
:meth:`__str__` so the arguments can be printed directly without having to
reference “.args“.
在异常名(列表)之后,也可以为 except 子句指定一个变量。这个变量绑定于
一个异常实例,它存储在 “instance.args“ 的参数中。为了方便起见,异常实例
定义了 :meth:`__str__` ,这样就可以直接访问过打印参数而不必引用
“.args“ 。
one may also instantiate an exception first before raising it and add any
attributes to it as desired. :
这种做法不受鼓励。相反,更好的做法是给异常传递一个参数(如果要传递多个
参数,可以传递一个元组),把它绑定到 message 属性。一旦异常发生,它会
在抛出前绑定所有指定的属性。 ::
>>> try:
… raise exception(‘spam’, ‘eggs’)
… except exception as 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
…
(‘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 zeropisionerror as detail:
… print ‘handling run-time error:’, detail
…
handling run-time error: integer pision or modulo by zero
.. _tut-raising:
raising exceptions 抛出异常
===========================
the :keyword:`raise` statement allows the programmer to force a specified
exception to occur. for example:
程序员可以用 :keyword:`raise` 语句强制指定的异常发生。例如 ::
>>> raise nameerror(‘hithere’)
traceback (most recent call last):
file “”, line 1, in ?
nameerror: hithere
the sole argument to :keyword:`raise` indicates the exception to be raised.
this must be either an exception instance or an exception class (a class that
derives from :class:`exception`).
要抛出的异常由 :keyword:`raise` 的唯一参数标识。它必需是一个异常实例或
异常类(继承自 :class:`exception` 的类)。
if you need to determine whether an exception was raised but don’t intend to
handle it, a simpler form of the :keyword:`raise` statement allows you to
re-raise the exception:
如果你需要明确一个异常是否抛出,但不想处理它, :keyword:`raise`
语句可以让你很简单的重新抛出该异常。
>>> try:
… raise nameerror(‘hithere’)
… except nameerror:
… print ‘an exception flew by!’
… raise
…
an exception flew by!
traceback (most recent call last):
file “”, line 2, in ?
nameerror: hithere
.. _tut-userexceptions:
user-defined exceptions 用户自定义异常
======================================
programs may name their own exceptions by creating a new exception class (see
:ref:`tut-classes` for more about python classes). exceptions should typically
be derived from the :exc:`exception` class, either directly or indirectly. for
example:
在程序中可以通过创建新的异常类型来命名自己的异常(python 类的内容请参
见 :ref:`tut-classes` )。异常类通常应该直接或间接的从
:exc:`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 as e:
… print ‘my exception occurred, value:’, e.value
…
my exception occurred, value: 4
>>> raise myerror(‘oops!’)
traceback (most recent call last):
file “”, line 1, in ?
__main__.myerror: ‘oops!’
in this example, the default :meth:`__init__` of :class:`exception` has been
overridden. the new behavior simply creates the *value* attribute. this
replaces the default behavior of creating the *args* attribute.
在这个例子中,:class:`exception` 默认的 :meth:`__init__` 被覆盖。新的方式简单的创建
value 属性。这就替换了原来创建 *args* 属性的方式。
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 that 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.”””
pass
class inputerror(error):
“””exception raised for errors in the input.
attributes:
expr — input expression in which the error occurred
msg — explanation of the error
“””
def __init__(self, expr, msg):
self.expr = expr
self.msg = msg
class transitionerror(error):
“””raised when an operation attempts a state transition that’s not
allowed.
attributes:
prev — state at beginning of transition
next — attempted new state
msg — explanation of why the specific transition is not allowed
“””
def __init__(self, prev, next, msg):
self.prev = prev
self.next = next
self.msg = msg
most exceptions are defined with names that end in “error,” similar to the
naming of the standard exceptions.
与标准异常相似,大多数异常的命名都以“error”结尾。
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 :ref:`tut-classes`.
很多标准模块中都定义了自己的异常,用以报告在他们所定义的函数中可能发生
的错误。关于类的进一步信息请参见 :ref:`tut-classes` 一章。
.. _tut-cleanup:
defining clean-up actions 定义清理行为
====================================================
the :keyword:`try` statement has another optional clause which is intended to
define clean-up actions that must be executed under all circumstances. for
example:
:keyword:`try` 语句还有另一个可选的子句,目的在于定义在任何情况下都一定要执行的功
能。例如 ::
>>> try:
… raise keyboardinterrupt
… finally:
… print ‘goodbye, world!’
…
goodbye, world!
traceback (most recent call last):
file “”, line 2, in ?
keyboardinterrupt
a *finally clause* is always executed before leaving the :keyword:`try`
statement, whether an exception has occurred or not. when an exception has
occurred in the :keyword:`try` clause and has not been handled by an
:keyword:`except` clause (or it has occurred in a :keyword:`except` or
:keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
been executed. the :keyword:`finally` clause is also executed “on the way out”
when any other clause of the :keyword:`try` statement is left via a
:keyword:`break`, :keyword:`continue` or :keyword:`return` statement. a more
complicated example (having :keyword:`except` and :keyword:`finally` clauses in
the same :keyword:`try` statement works as of python 2.5):
不管有没有发生异常, *finally 子句* 在程序离开 :keyword:`try` 后都一定
会被执行。当 :keyword:`try` 语句中发生了未被 :keyword:`except` 捕获的
异常(或者它发生在 :keyword:`except` 或 :keyword:`else` 子句中),在
:keyword:`finally` 子句执行完后它会被重新抛出。 :keyword:`try` 语句经
由 :keyword:`break` ,:keyword:`continue` 或 :keyword:`return` 语句退
出也一样会执行 :keyword:`finally` 子句。以下是一个更复杂些的例子(在同
一个 :keyword:`try` 语句中的 :keyword:`except` 和 :keyword:`finally`
子句的工作方式与 python 2.5 一样) ::
>>> def pide(x, y):
… try:
… result = x / y
… except zeropisionerror:
… print “pision by zero!”
… else:
… print “result is”, result
… finally:
… print “executing finally clause”
…
>>> pide(2, 1)
result is 2
executing finally clause
>>> pide(2, 0)
pision by zero!
executing finally clause
>>> pide(“2”, “1”)
executing finally clause
traceback (most recent call last):
file “”, line 1, in ?
file “”, line 3, in pide
typeerror: unsupported operand type(s) for /: ‘str’ and ‘str’
as you can see, the :keyword:`finally` clause is executed in any event. the
:exc:`typeerror` raised by piding two strings is not handled by the
:keyword:`except` clause and therefore re-raised after the :keyword:`finally`
clause has been executed.
如你所见, :keyword:`finally` 子句在任何情况下都会执
行。 :exc:`typeerror`
在两个字符串相除的时候抛出,未被 :keyword:`except` 子句捕获,因此在
:keyword:`finally` 子句执行完毕后重新抛出。
in real world applications, the :keyword:`finally` clause is useful for
releasing external resources (such as files or network connections), regardless
of whether the use of the resource was successful.
在真实场景的应用程序中, :keyword:`finally` 子句用于释放外部资源(文件
或网络连接之类的),无论它们的使用过程中是否出错。
.. _tut-cleanup-with:
predefined clean-up actions 预定义清理行为
=======================================================
some objects define standard clean-up actions to be undertaken when the object
is no longer needed, regardless of whether or not the operation using the object
succeeded or failed. look at the following example, which tries to open a file
and print its contents to the screen. :
有些对象定义了标准的清理行为,无论对象操作是否成功,不再需要该对象的时
候就会起作用。以下示例尝试打开文件并把内容打印到屏幕上。 ::
for line in open(“myfile.txt”):
print line
the problem with this code is that it leaves the file open for an indeterminate
amount of time after the code has finished executing. this is not an issue in
simple scripts, but can be a problem for larger applications. the
:keyword:`with` statement allows objects like files to be used in a way that
ensures they are always cleaned up promptly and correctly. :
这段代码的问题在于在代码执行完后没有立即关闭打开的文件。这在简单的脚本
里没什么,但是大型应用程序就会出问题。 :keyword:`with` 语句使得文件之类的对象可以
确保总能及时准确地进行清理。 ::
with open(“myfile.txt”) as f:
for line in f:
print line
after the statement is executed, the file *f* is always closed, even if a
problem was encountered while processing the lines. other objects which provide
predefined clean-up actions will indicate this in their documentation.
语句执行后,文件 *f* 总会被关闭,即使是在处理文件中的数据时出错也一样。
其它对象是否提供了预定义的清理行为要查看它们的文档。
以上就是python 2.7基础教程之:错误和异常的内容,更多相关内容请关注php中文网(www.php1.cn)!