在装饰器中捕获异常

时间:2019-05-19 10:04:36

标签: python exception decorator python-decorators

从理论上讲,这个问题可能不是正确的,但想知道是否有任何解决方法。

让我们考虑以下示例:

def my_function():
    try:
        print("before the exception occurs")
        raise ValueError
    except ValueError:
        print('exception found')

    print("after the exception occurs")


if __name__ == "__main__":
    my_function()

如果打印到标准输出,输出应如下所示:

before the exception occurs
exception found
after the exception occurs

但是,如果使用装饰器来捕获如下异常:

from functools import wraps


def decorator(func):
  @wraps(func)
  def wrapper(*args, **kwargs):
    try:
        return func(*args, **kwargs)
    except ValueError:
        print('exception found')

  return wrapper


@decorator
def my_exception_function():
  print("before the exception occurs")

  raise ValueError

  print("after the exception occurs")


if __name__ == "__main__":
  my_exception_function()

发生异常后的其余功能将不会按以下方式执行:

before the exception occurs
exception found

因此,我想知道是否可以使用任何解决方法来获取第一个示例输出,但可以使用装饰器来捕获异常。

1 个答案:

答案 0 :(得分:2)

让我们尝试将my_exception_func内联到装饰器中。

from functools import wraps


def decorator(func):
  @wraps(func)
  def wrapper(*args, **kwargs):
    try:
        print("before the exception occurs")
        raise ValueError
        print("after the exception occurs")
    except ValueError:
        print('exception found')

  return wrapper

所以现在控制流程应该更加清晰:

  • 在“例外之前”打印
  • 引发异常
  • 转到except block
  • 返回

由于出现异常,所以永远无法达到“异常后”打印。

使用try-except块来捕获异常,但是在异常点之后执行代码并不能真正起作用。您需要完全隔离可能发生异常的位置,并将该部分仅包装在try-except块中。