Search code examples
functionpython-2.7returntry-finally

Why is Finally executed after return statement?


def Test():
    try:
        return 0
    finally:
        return 1
x  = Test()
print(x)

Why is the output for above code 1 ? https://code.hackerearth.com/5cc081y Although logically the control leaves the function at the return statement.


Solution

  • https://docs.python.org/2/tutorial/errors.html

    "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.