Search code examples
pythonexceptiontry-catchtry-catch-finally

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?

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?


Clearer with this example:

def f():
    try:
        1/0
        # 1/1
    except:
        print('except')    #1
        raise print("a")   #2  # nonsense but just to see in which order this line is executed         
    finally:
        print('finally')   #3

which gives

except
a
finally
foo

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.