Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order of execution in try except finally

I never really use finally, so I wanted to test a few things before using it more regularly. I noticed that when running:

def f():
    try:
        1/0
        # 1/1
    except:
        print('except')      # 1
        raise                # 2
    finally:
        print('finally')     # 3

try:
    f()
except:
    print("haha")

we get this order of execution:

except
finally
haha

What is the rule for the order of excution?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

From what I see I get this rule:

  • run everything in the except block, but not the raise statement, if any such statement is present
  • run the finally block
  • go back to the except block, and run the last raise statement, if present

Is that correct?

Are there other statements than raise in an except block that can be postponed after the finally block?

>Solution :

According to [Python.Docs]: Errors and Exceptions – Defining Clean-up Actions (emphasis is mine, read all the bullets though):

  • An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.

So that’s the expected behavior.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading