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 ? KeyboardInterrupt
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 子句经由 break 或 return 退出也一样会执行 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 子句,但两者不能共存。