Oracle 系统管理 - Linux 系统 - Backtrack 5 - 安全 - Juniper 技术 - Cisco 技术 - 思科模拟器 - Cisco 认证 - Cisco ios 下载

您现在的位置是:Docker > Python运维 > Python 2.7 Tutorial —— 错误和异常

Python 2.7 Tutorial —— 错误和异常

时间:2018-06-09 15:18  来源:未知  阅读次数: 复制分享 我要评论

.. _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 "<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 :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 "<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 :exc:`ZeroDivisionError`, :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:`ZeroDivisionError` ) ,命名错误( :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

   ...

   <type 'exceptions.Exception'>

   ('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 as detail:

   ...     print 'Handling run-time error:', detail

   ...

   Handling run-time error: integer division 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 "<stdin>", 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 "<stdin>", 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 "<stdin>", 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 "<stdin>", 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 divide(x, y):

   ...     try:

   ...         result = x / y

   ...     except ZeroDivisionError:

   ...         print "division by zero!"

   ...     else:

   ...         print "result is", result

   ...     finally:

   ...         print "executing finally clause"

   ...

   >>> divide(2, 1)

   result is 2

   executing finally clause

   >>> divide(2, 0)

   division by zero!

   executing finally clause

   >>> divide("2", "1")

   executing finally clause

   Traceback (most recent call last):

     File "<stdin>", line 1, in ?

     File "<stdin>", line 3, in divide

   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 dividing 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* 总会被关闭,即使是在处理文件中的数据时出错也一样。

其它对象是否提供了预定义的清理行为要查看它们的文档。