简体   繁体   中英

Python how to exclude exceptions from “catch all”

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM