-1

I would expect myfunction to return 0 and not execute the finally but why does it do so?

def myfunction(i):
    try:
        result=10/i
    except:
        return 0
    finally:
        return 10 

print(myfunction(0))
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Teererai Marange
  • 2,044
  • 4
  • 32
  • 50

3 Answers3

0

the code in the finally section will run no matter what happens in the catch block ( except for the times that your program terminates somehow before reaching the finally section) if you want for it not to run you should alter your code like this:

def myfunction(i):
    try:
        result=10/i
    except:
        return 0
    return 10
Arya11
  • 570
  • 2
  • 6
  • 21
0

finally is always executed, regardless exception occurred or not. The documentation is very clear in that essence:

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause), it is re-raised after the finally clause has been executed.

So the return statement in the finally clause overrides the one from the exception clause. It doesn't make much sense to put return statement inside a finally clause, as this would be the only value returned from a function.

Chen A.
  • 10,140
  • 3
  • 42
  • 61
0

It returns 10 because the finally clause in your try block executes before any return statement as shown in this answer.

It's also worth noting that you're using the generic except which will result in a lot of unintended behaviour. Check this answer for how to best construct try/except blocks and best raise exceptions.

aydow
  • 3,673
  • 2
  • 23
  • 40