从python __exit__块中重新分配异常 [英] Re-assign exception from within a python __exit__ block

查看:379
本文介绍了从python __exit__块中重新分配异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在自定义游标类中的 __ exit __ 块内,我想捕获一个异常,因此我可以反过来抛出一个更具体的异常。什么是正确的方法?

From within an __exit__ block in a custom cursor class I want to catch an exception so I can in turn throw a more specific exception. What is the proper way to do this?

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 __ block似乎是一个黑客,但也许我在想。

Raising the specific exception within the __exit__ block seems like a hack, but maybe I'm over thinking it.

推荐答案

正确的过程是在 __ exit __ 处理程序之内引发新异常。

The proper procedure is to raise the new exception inside of the __exit__ handler.

您应该不要引发了通过的异常;允许上下文管理器链接,在这种情况下,你应该只是从处理程序返回一个假的值。提出自己的例外情况是非常好的。

You should not raise the exception that was passed in though; to allow for context manager chaining, in that case you should just return a falsey value from the handler. Raising your own exceptions is however perfectly fine.

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

Note that it is better to use the identity test is to verify the type of the passed-in exception:

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)允许特定异常的子类。

You could also use issubclass(ex_type, VagueThirdPartyError) to allow for subclasses of the specific exception.

这篇关于从python __exit__块中重新分配异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆