I want to catch exception that was raised inside context manager. I created simple example to reproduce the problem.
So, my context manager:
class Test(object):
def div(self, a, b):
return a // b
def __enter__(self):
print('enter')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
return self
And class where I want to use it:
class Container(object):
def test_exc(self, a, b):
try:
with Test() as test:
try:
result = test.div(a, b)
print(a, '/', b, '=', result)
return result
except Exception as e:
raise e
except Exception as e:
print(e)
Usage:
c = Container()
c.test_exc(5, 1)
c.test_exc(5, 0)
The output:
enter
5 / 1 = 5
exit
enter
exit
So, when exception raised (in example above it's ZeroDivisionError) it's not catched by parent try...catch. How to fix this ?