I know raise ... from Noneand read. How can I more easily suppress previous exceptions when I raise my own exception in response? .
However, how can I achieve the same effect (suppressing the message "While processing the above exception, another exception") without control over the code that is executed from the except clause? I thought you could use this sys.exc_clear(), but this function does not exist in Python 3.
Why am I asking about this? I have a simple caching code that looks (simplified):
try:
value = cache_dict[key]
except KeyError:
value = some_api.get_the_value_via_web_service_call(key)
cache_dict[key] = value
When an exception occurs in the API call, the output will be something like this:
Traceback (most recent call last):
File ..., line ..., in ...
KeyError: '...'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File ..., line ..., in ...
some_api.TheInterestingException: ...
, KeyError . , , , try/except (EAFP) (LBYL), Pythonic ( , -, , ).
, some_api raise X raise X from None ( ). , ?
(, : -, , cache_dict.setdefault(key, some_api.get_the_value_via_web_service_call(key)), setdefault , , . / ?)