-2

I'm wondering why the function foo is returning 3 instead 1. Please explain.

def foo():
    try:
        return 1
    except:
        return 2
    finally:
        return 3
nik_kgp
  • 1,112
  • 1
  • 9
  • 17

2 Answers2

1

The finally block executes regardless of Exceptions. Take a look at this question.

To elaborate, the finally clause is always executed before the end of the try statement. Here is the documentation.

Community
  • 1
  • 1
  • But how does it skip the `return 1`? – TheSoundDefense Aug 05 '14 at 14:18
  • In the mentioned try-block, no exception is being raised. – nik_kgp Aug 05 '14 at 14:20
  • Yes, but the point is that the finally block executes before leaving the try statement. No idea why people have downvoted this, it's correct. And since there's a return statement in the finally block, the entire function exits. If there wasn't, it would go back to the try statement, try it and continue based on whether there was an exception or not. –  Aug 05 '14 at 14:22
  • 1
    @TheSoundDefense it's "paused" while the `finally` block runs (as it is guaranteed to always do), then because of the `return` in that block never gets "unpaused" (as the function is now over). – jonrsharpe Aug 05 '14 at 14:23
0

Finally is always the last item to happen after executing a try block.

Yes, the finally block is executed however the flow leaves the try block - whether by reaching the end, returning, or throwing an exception.