Python Forum

Full Version: finally clause
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
documentation says that the code in a finally: clause gets run whether the exception happens, or not. what is the difference between using finally: and just putting your code after the whole try: ... except: as long as you don't use continue or return and flow of control always comes to the next statement?
Short answer: finally always runs (common usage of try/finally is for reliably closing file handles and other setups-teardowns).

try/finally is used when one want exceptions to propagate up, but also to run cleanup code even when exceptions occur.
Finally is always executed, regardless what happens before:

#!/usr/bin/python3
import random

def action():
    try:
        print("try")
        r = random.randint(0,3)
        if r == 0:
            print("exit")
            exit()
        elif r == 1:
            print("return")
            return
        elif r == 2:
            print("raise")
            raise Exception()
        else:
            print("pass")
    finally:
        print("finally")

#main
try:
    action()
except:
    pass
Same question has been asked before on the forum.
https://python-forum.io/Thread-try-except-finally
so if the exception might happen, finally: assures that you can close/teardown while not actually handling the exception, or doing continue/return/break in except:. unless using continue/return/break i see following code as equivalent. but have been assuming their would always be an except:. now i understand there might not be, and there are 4 ways to change flow, the 3 statements continue, return, break, and the lack of except: (exception causing the flow change). yet another reason to be happy there is no goto.
You can also look at chapter Errors and Exeptions at python.org (explanations and sample code)
(Jun-02-2019, 08:34 PM)Skaperen Wrote: [ -> ]so if the exception might happen, finally: assures that you can close/teardown while not actually handling the exception
Yes,and we use it all time even if not always see it.
with open() has been then preferred way do deal with files since it came out in Python 2.5.
with open('some_file', 'w') as f:
    f.write('Hello!')
The underlying code is this.
f = open('some_file', 'w')
try:
    f.write('Hello!')
finally:
    f.close()
Now is there also __enter__ and __exit__ special methods to make with.
But the important part is that the file is always closed because of no except and finally(deal with all cases for closing the file).