10.6 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:
... 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.
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.
A try statement must either have one or more except clauses
or one finally clause, but not both.
|