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?
The
finally
clause will always execute which is great if you missed an exception type in your code.To quote the documentation:
The
finally
suite is guaranteed to be executed, whatever happens in thetry
suite.Use it to clean up files, database connections, etc:
This is true regardless of whether an exception handler (
except
suite) catches the exception or not, or if there is areturn
statement in your code:Using a
try
/finally
statement in a loop, then breaking out of the loop with eithercontinue
orbreak
would, again, execute thefinally
suite. It is guaranteed to be executed in all cases.