What's the scope of using the 'finally' clause in python?

python, try-finally

Solution

The `finally` suite is guaranteed to be executed, whatever happens in the `try` suite.

Use it to clean up files, database connections, etc:

try:
    file = open('frobnaz.txt', 'w')
    raise ValueError
finally:
    file.close()
    os.path.remove('frobnaz.txt')

This is true regardless of whether an exception handler (`except` suite) catches the exception or not, or if there is a `return` statement in your code:

def foobar():
    try:
        return
    finally:
        print "finally is executed before we return!"

Using a `try`/`finally` statement in a loop, then breaking out of the loop with either `continue` or `break` would, again, execute the `finally` suite. It is guaranteed to be executed in all cases.

Problem

Possible Duplicate: Purpose of else and finally in exception handling I'd like to understand why the `finally` clause exists in the `try/except` statement. I understand what it does, but clearly I'm missing something if it deserves a place in the language. Concretely, what's the difference between writing a clause in the `finally` field with respect of writing it outside the `try/except` statement?

Original source

Related problems