exception_guard context manager and decorator
Steve D'Aprano
steve+python at pearwood.info
Sun Jun 25 13:26:08 EDT 2017
As discussed in the Python-Ideas mailing list, sometimes we want to suppress a
particular kind of exception and replace it with another.
For that reason, I'd like to announce exception_guard, a context manager and
decorator which catches specified exceptions and replaces them with a given
exception (RuntimeError by default).
https://code.activestate.com/recipes/580808-guard-against-an-exception-in-the-wrong-place/
or just
https://code.activestate.com/recipes/580808
It should work with Python 2.6 through 3.6 and later.
try:
with exception_guard(ZeroDivisionError):
1/0 # raises ZeroDivisionError
except RuntimeError:
print ('ZeroDivisionError replaced by RuntimeError')
See the recipe on ActiveState for links to discussions on Python-Ideas.
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list