Skip to content
Advertisement

Python confusion with return value in try-except-finally

Here is a piece of my code:

def main():
    num = 0
    try:
        raise Exception('This is the error message.')
    except Exception:
        num += 1
        return num
    finally:
        num += 1

a = main()
print(a)

The returning value is 1 instead of 2, this does not make a lot of sense for me.

I thought it would return 2 since finally should execute before returning the value.

Can someone help me to understand this?

Advertisement

Answer

You’re running into the difference between an identifier and a value. num += 1 is creating a new int object and assigning the num identifier to point to it. It does not change the int object the identifier is already pointing to. (For small values the int objects are cached but that’s an implementation detail)

You can see the difference with an operation that does mutate the object in the below code:

def y():
    l = []
    try:
        raise Exception
    except Exception:
        print("except")
        l.append(1)
        return l
    finally:
        print("finally")
        l.append(2)

print(y())
# except
# finally
# [1, 2]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement