Search code examples
pythonexceptioncontextmanager

python swallow exception in context manager and go on


I want to write a context manager which can swallow the given exceptions and GO ON.

class swallow_exceptions(object):
    def __init__(self, exceptions=[]):
        self.allowed_exceptions = exceptions

    def __enter__(self):
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        if exception_type in self.allowed_exceptions:
            print(f"{exception_type.__name__} swallowed!")
            return True

It swallows the ZeroDivisonError as expected but then it terminates from the ContextManager because of the return True statement in the '__exit__' method.

with swallow_exceptions([ZeroDivisionError]):
   error_1 = 1 / 0
   error_2 = float("String") # should raise ValueError!

Is there a way to catch the exception and then go on? I tried with 'yield True' but it terminated without printing anything at all.


Solution

  • There's no way to continue running the body of the with statement after an exception makes it back to the context manager. The context manager can stop the exception from bubbling up further, but it can't do more than that.

    What you might want is to use your context manager in several separate with statements:

    suppress = swallow_exceptions([ZeroDivisionError])
    
    with suppress:
        1 / 0              # this exception is suppressed
    
    with suppress:
        float("String")  # this one is not