James Lin
James Lin

Reputation: 26528

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

Upvotes: 1

Views: 1376

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375484

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

Upvotes: 2

Related Questions