I tried googling it but couldn't find a similar problem. I am sure it's something silly but I can't seem to get it.
I have the following code:
def f(a):
try:
4 / a
except:
f(2)
else:
print('else')
finally:
print("finally")
When I call the function with 0 as the argument: f(0)
It returns:
else
finally
finally
So in my understanding here is what should happen:
elsefinallyWhy does finally gets printed twice?
When you invoke with f(0), the finally block is called twice. Once for the call to f(2) and then again for the enclosing call to f(0).
This is because 4 / 0 leads to an exception, which triggers the second call to f via f(2).
finally will be invoked first for the call to f(2), then for the call to f(0) - because f(2) is invoked from f(0).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With