Skip to content Skip to sidebar Skip to footer

Catching An Exceptions In __enter__ In The Calling Code In Python

Is there a way I can catch exceptions in the __enter__ method of a context manager without wrapping the whole with block inside a try? class TstContx(object): def __enter__(sel

Solution 1:

You can catch the exception using try/except inside of __enter__, then save the exception instance as an instance variable of the TstContx class, allowing you to access it inside of the with block:

classTstContx(object):
    def__enter__(self):
        self.exc = Nonetry:
            raise Exception("I'd like to catch this exception")
        except Exception as e:
            self.exc = e 
        return self

    def__exit__(self, e_typ, e_val, trcbak):
        passwith TstContx() as tst:
    if tst.exc:
        print("We caught an exception: '%s'" % tst.exc)
    raise Exception("I don't want to catch this exception")

Output:

We caught an exception: 'I'd like to catch this exception'.
Traceback (most recent call last):
  File "./torn.py", line 20, in <module>
    raise Exception("I don't want to catch this exception")
Exception: I don't want to catch this exception

Not sure why you'd want to do this, though....

Solution 2:

You can use contextlib.ExitStack as outlined in this doc example in order to check for __enter__ errors separately:

from contextlib import ExitStack

stack = ExitStack()
try:
    stack.enter_context(TstContx())
except Exception:  # `__enter__` produced an exception.passelse:
    with stack:
        ...  # Here goes the body of the `with`.

Post a Comment for "Catching An Exceptions In __enter__ In The Calling Code In Python"