The execution order of return statement in try except else finally in Python

The execution order of return statement in try except else finally in Python

Python version: 3.7

First, let’s take a look at the example of try except else finally

def exe_try():
    try:
        print("start")
        raise KeyError
        return 1
    except KeyError as e:
        print("key error")
        return 2
    else:
        print("other")
        return 3
    finally:
        print("finally")
        # return 4


result = exe_try()
print(result)
# You can see that the result of its execution is:
# start
# key error
# finally
# 4
# exe_try function catches the KeyError exception, but why does it not return 2 but 4?
# Here is the use of the return statement in try except finally:
# If there is a return statement in finally, it returns the return statement in finally,
# If finally does not have a return statement, it returns the return statement from the previous call
# Execution process:
# When the exe_try function is executed, it prints start, and then encounters a KeyError exception.
# Then the exception is caught and the code block in except is executed: the key error is printed, and return 2 is executed
# But this return 2 does not return directly, but put it on the stack
# Then it goes on to the next block in finally: prints finally, and executes return 4
# Here it still doesn't return 4 directly, but puts it on the stack as well
# At this point the entire try except else finally are executed, it will take out the return at the top of the stack and return
# And the return in finally is put on the stack afterwards, so it's on the top of the stack, and returns 4.

# If there is no return statement in finally, it will return:
# start
# key error
# finally
# 2

Similar Posts: