+ 5
Confusion in exception handling
def num(): try: return 1 finally: return 2 print(num()) OUTPUT : 2(why 2...why not 1)
4 Answers
+ 4
It will always go to the finally block no matter what happens, so it will ignore the returns in the try and except block. If you would have a return above the try and except, it would return that value.
def func1():
try:
return 1 # ignoring the return
finally:
return 2 # returns this return
def func2():
try:
raise ValueError()
except:
# is going to this exception block, but ignores the return because it needs to go to the finally
return 1
finally:
return 3
def func3():
return 0 # finds a return here, before the try except and finally block, so it will use this return
try:
raise ValueError()
except:
return 1
finally:
return 3
func1() # returns 2
func2() # returns 3
func3() # returns 0
+ 1
because there is nothing except return in the try block?and the finally MUST always get excecuted
+ 1
because there is nothing except return in the try block?and the finally MUST always get excecuted
0
Same here... Still don't understand it...