【问题标题】:Re-assign exception from within a python __exit__ block从 python __exit__ 块中重新分配异常
【发布时间】:2013-03-11 16:46:59
【问题描述】:

从自定义游标类的__exit__ 块中,我想捕获一个异常,这样我就可以反过来抛出一个更具体的异常。这样做的正确方法是什么?

class Cursor:
    def __enter__(self):
        ...

    def __exit__(self, ex_type, ex_val, tb):
        if ex_type == VagueThirdPartyError:
            # get new more specific error based on error code in ex_val and
            # return that one in its place.
            return False # ?
        else:
            return False

__exit__ 块中提出特定异常似乎是一种 hack,但也许我想多了。

【问题讨论】:

  • 为什么只提出异常看起来像是一种黑客行为?
  • 我认为可能有另一种方法可以做到这一点,因为上下文管理器会捕获主块中的任何异常,将其存储,然后将其传递给 exit 以进行批准或否决。在exit内加注似乎更像是根据其论点扩大其职责-但我显然想多了。

标签: python exception-handling with-statement


【解决方案1】:

正确的过程是在 __exit__ 处理程序中引发新异常。

您应该引发传入的异常;为了允许上下文管理器链接,在这种情况下,您应该只从处理程序返回一个错误的值。然而,提出你自己的例外是完全没问题的。

注意最好使用身份测试is来验证传入异常的类型:

def __exit__(self, ex_type, ex_val, tb):
    if ex_type is VagueThirdPartyError:
        if ex_val.args[0] == 'foobar':
            raise SpecificException('Foobarred!')

        # Not raising a new exception, but surpressing the current one:
        if ex_val.args[0] == 'eggs-and-ham':
            # ignore this exception
            return True

        if ex_val.args[0] == 'baz':
            # re-raise this exception
            return False

    # No else required, the function exits and `None` is  returned

您也可以使用issubclass(ex_type, VagueThirdPartyError) 来允许特定异常的子类。

【讨论】:

  • 或者可能:if issubclass(ex_type,VagueThirdPartyError)
  • tl;dr 适用于 Google 员工:自定义 __exit__ 不传播异常?不要返回任何东西/返回虚假值。
猜你喜欢
  • 2022-01-05
  • 1970-01-01
  • 2023-03-31
  • 2011-03-02
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多