Python try finally block returns

skybobbi picture skybobbi · Nov 6, 2013 · Viewed 76.5k times · Source

There is the interesting code below:

def func1():
    try:
        return 1
    finally:
        return 2

def func2():
    try:
        raise ValueError()
    except:
        return 1
    finally:
        return 3

func1()
func2()

Could please somebody explain, what results will return these two functions and explain why, i.e. describe the order of the execution

Answer

lejlot picture lejlot · Nov 6, 2013

From the Python documentation

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement. A more complicated example (having except and finally clauses in the same try statement works as of Python 2.5):

So once the try/except block is left using return, which would set the return value to given - finally blocks will always execute, and should be used to free resources etc. while using there another return - overwrites the original one.

In your particular case, func1() return 2 and func2() return 3, as these are values returned in the finally blocks.