Python how to exclude exceptions from “catch all”

拟墨画扇 提交于 2019-12-25 16:47:00

问题


Lets say I have this:

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()

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()

回答1:


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()


来源:https://stackoverflow.com/questions/27030716/python-how-to-exclude-exceptions-from-catch-all

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