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.

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to