当包装函数中没有异常时,不调用 else 块

问题描述 投票:0回答:1

在下面的代码中,当

bar
没有引发异常时,我期望调用装饰器的
else
块,但这并没有发生。

#!/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()

bar
没有引发任何异常时的输出:

error flag set as true
Error seen in finally

为什么这里缺少

print("else block hit")

python python-decorators try-except
1个回答
0
投票

类似的 try - else 异常处理代码可以从中获得灵感:

    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")

因为你的try没有异常,所以它只是跳过了else条件。

© www.soinside.com 2019 - 2024. All rights reserved.