Re-assign exception from within a python __exit__ block

大兔子大兔子 提交于 2019-11-30 08:48:36

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!