In below code, when there is no exception raised from bar, I am expecting the else block of decorator to be called, but this is not happening.
#!/usr/bin/python
from functools import wraps
def handle_exceptions(func):
@wraps(func)
def wrapper(*arg, **kwargs):
try:
errorFlag = True
print("error flag set as true")
return func(*arg, **kwargs)
except Exception:
raise
else:
print("else block hit")
errorFlag = False
finally:
if errorFlag:
print("Error seen in finally")
return wrapper
def bar():
pass
@handle_exceptions
def foo():
bar()
foo()
Output when bar does not raise any exceptions:
error flag set as true
Error seen in finally
Why is print("else block hit") missing here?
A similar try - else, exception handling code to get inspired from:
Because your try block had no errors or exceptions and you are using return, you code will simply skip the else condition.