The try statement has optional finally
clause that must be executed under all circumstances. For example:
>>> try: ... raise KeyboardInterrupt ... finally: ... print 'Goodbye, world!' ... Goodbye, world! KeyboardInterrupt
Here’s another example:
>>> 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'
The finally
clause is indented to define clean-up actions.
For example, if you opened a file and an exception was raised after opening it, you always want to close the file.
The finally
clause is especially useful when you want to release external resources.