0

Can someone please explain me why does this work like it does? Python 3.6.3

In [1]: def test():
   ...:     try:
   ...:         return 1
   ...:     finally:
   ...:         return 2
   ...:     

In [2]: test()
Out[2]: 2

EDIT: This is not exactly duplicate as linked questions raise exceptions in their try : and my example uses return which I expected to work. This function looks like it should return 1 yet it returns 2 - so basically return 1 is ignored. finally makes a good job of eating any risen exceptions but should it also eat returns?

minder
  • 2,059
  • 5
  • 24
  • 39
  • 4
    As `finally` will be executed without any exception, I think in this case the statement in `try` is executed but the value doesn't return. – Sraw Aug 03 '18 at 12:30
  • 1
    This answer in the duplicate is valid both for `return` and for exceptions. https://stackoverflow.com/a/11164157/1977847 – Håken Lid Aug 04 '18 at 12:09

1 Answers1

4

Because finally is a cleaning up action that is always excuted if added in a try, except,else, finally ;)

You can read Python 3 documentation’s page on Error handlings here:https://docs.python.org/3/tutorial/errors.html

Section: 8.6. Defining Clean-up Actions

Prayson W. Daniel
  • 14,191
  • 4
  • 51
  • 57