Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
finally clause
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
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
Reply
#4
Same question has been asked before on the forum.
https://python-forum.io/Thread-try-except-finally
Reply
#5
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
You can also look at chapter Errors and Exeptions at python.org (explanations and sample code)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
(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).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to use the LIKE clause in Python Columbo 9 1,617 Oct-09-2022, 10:22 PM
Last Post: Larz60+
  SQL Query is not executing WHERE clause hammer 7 2,319 Nov-15-2021, 01:44 PM
Last Post: hammer
  How does this if clause work? Pedroski55 3 2,260 Jun-10-2021, 06:31 AM
Last Post: Gribouillis
  Help with try, except, else finally Pytho13 14 5,042 Mar-23-2021, 05:35 PM
Last Post: snippsat
  Am I a retard - else and finally blocks in a try statement RubenF85 6 2,570 Jan-12-2021, 05:56 PM
Last Post: bowlofred
  can i raise an exception in a try clause? Skaperen 14 5,710 Dec-19-2019, 12:29 AM
Last Post: Skaperen
  pass captured value from input() to where clause metro17 5 3,261 Sep-09-2019, 05:24 AM
Last Post: metro17
  try, except, finally ? microphone_head 3 2,839 Apr-28-2019, 09:36 PM
Last Post: microphone_head
  if clause fails DeadCthulhuWaitsDreaming 10 4,727 Apr-07-2019, 09:19 PM
Last Post: DeadCthulhuWaitsDreaming
  how to code in Python "where" clause of SAS FelixS 2 2,782 Mar-26-2019, 04:59 PM
Last Post: FelixS

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020