1

I have the following sample function:

def test():
    try:
        try:
            x =1
        except:
            x = 2
        finally:
            print('X')
            x = 7
            return x
    except Exception:
        x=2
    finally:
        x = 9
        return x

print(test())

Based on this, I would expect that test() always returns 7 (first return), but instead it returns 9, even though it reached the x=7 line ('X' is printed). How can this be?

kederrac
  • 16,819
  • 6
  • 32
  • 55
Jano
  • 455
  • 2
  • 9
  • May be this [post](https://stackoverflow.com/questions/11164144/weird-try-except-else-finally-behavior-with-return-statements/11164157) would be helpfull. – Chanda Korat Mar 24 '20 at 09:51

1 Answers1

3

from the docs:

If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception.

(...)

  • If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the
    value from the try clause’s return statement.

you may think that you have 2 finally clauses but the first one is included in the first try clause so it does make sense that your function returns 9

kederrac
  • 16,819
  • 6
  • 32
  • 55