从python __exit__块中重新分配异常

jpr*_*ham 12 python exception-handling with-statement

__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
Run Code Online (Sandbox Code Playgroud)

提升__exit__块内的特定异常看起来像是一个黑客,但也许我在想它.

Mar*_*ers 18

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

你应该提高那是虽然通过除外; 允许上下文管理器链接,在这种情况下,您应该只从处理程序返回一个falsey值.然而,提高自己的例外是完全正常的.

请注意,最好使用身份测试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
Run Code Online (Sandbox Code Playgroud)

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

  • 或者可能:`if issubclass(ex_type,VagueThirdPartyError)` (5认同)
  • **tl; dr**for Googlersrs:自定义`__exit__`不传播异常?不要返回任何东西/返回虚假值. (3认同)