Why do we need the "finally" clause in Python?
It makes a difference if you return early:
try: run_code1()except TypeError: run_code2() return None # The finally block is run before the method returnsfinally: other_code()
Compare to this:
try: run_code1()except TypeError: run_code2() return None other_code() # This doesn't get run if there's an exception.
Other situations that can cause differences:
- If an exception is thrown inside the except block.
- If an exception is thrown in
run_code1()but it's not a
- Other control flow statements such as
You can use
finally to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception. (Or if you don't catch that specific exception.)
myfile = open("test.txt", "w")try: myfile.write("the Answer is: ") myfile.write(42) # raises TypeError, which will be propagated to callerfinally: myfile.close() # will be executed before TypeError is propagated
In this example you'd be better off using the
with statement, but this kind of structure can be used for other kinds of resources.
A few years later, I wrote a blog post about an abuse of
finally that readers may find amusing.
They are not equivalent. Finally code is run no matter what else happens. It is useful for cleanup code that has to run.