8.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 (innermost last):
  File "<stdin>", line 2
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.

A try statement must either have one or more except clauses or one finally clause, but not both.


guido@python.org