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
finallysuite is guaranteed to be executed, whatever happens in thetrysuite.Use it to clean up files, database connections, etc:
This is true regardless of whether an exception handler (
exceptsuite) catches the exception or not, or if there is areturnstatement in your code:Using a
try/finallystatement in a loop, then breaking out of the loop with eithercontinueorbreakwould, again, execute thefinallysuite. It is guaranteed to be executed in all cases.