else block not invoked when there is no exception in wrapped function

68 Views Asked by At

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?

1

There are 1 best solutions below

3
TkrA On

A similar try - else, exception handling code to get inspired from:

    try:
        # Code that may raise an exception
        x = 5 / 0
    except ZeroDivisionError:
        # Handle the exception
        print("Division by zero is not allowed")
    else:
        # Execute if no exception is raised
        print("Division was successful")
    finally:
        # Always execute, regardless of an exception
        print("This will always be executed")

Because your try block had no errors or exceptions and you are using return, you code will simply skip the else condition.