问题
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