本文介绍了Python如何从&"catch all&"中排除异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说:

try:
    result = call_external_service()
    if not result == expected:
        raise MyException()
except MyException as ex:
    # bubble up
    raise ex
except Exception:
    # unexpected exceptions from calling external service
    do_some_logging()

由于我有限的python知识,我无法想到一种优雅的方式来冒起 MyException 异常,我希望可以做类似的事情:

Due to my limited python knowledge, I cannot think of an elegant way to bubble up the MyException exception, I was hoping I can do something like:

try:
    result = call_external_service()
    if not result == expected:
        raise MyException()
except Exception, exclude(MyException):
    # unexpected exceptions from calling external service
    do_some_logging()

推荐答案

您的问题似乎是您在try块中包装了太多代码.那怎么办呢?:

Your problem seems to be that you are wrapping too much code in your try block. What about this?:

try:
    result = call_external_service()
except Exception:
    # unexpected exceptions from calling external service
    do_some_logging()

if result != expected:
    raise MyException()

这篇关于Python如何从&"catch all&"中排除异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 12:29