好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python2.7基础教程之:错误和异常

.. _tut-errors:

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

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

以上就是Python 2.7基础教程之:错误和异常的内容,更多相关内容请关注PHP中文网(HdhCmsTestgxlcms测试数据)!

查看更多关于Python2.7基础教程之:错误和异常的详细内容...

  阅读:34次