Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading