+ 5

Confusion in exception handling

def num(): try: return 1 finally: return 2 print(num()) OUTPUT : 2(why 2...why not 1)

25th Jan 2018, 6:40 PM
Tilok Saha
Tilok Saha - avatar
5 Antworten
+ 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
26th Jan 2018, 7:43 PM
Tilok Saha
Tilok Saha - avatar
+ 1
because there is nothing except return in the try block?and the finally MUST always get excecuted
25th Jan 2018, 6:45 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 1
because there is nothing except return in the try block?and the finally MUST always get excecuted
25th Jan 2018, 6:45 PM
᠌᠌Code X
᠌᠌Code X - avatar
0
Same here... Still don't understand it...
26th Jan 2018, 7:05 PM
Fernando Lima
Fernando Lima - avatar