Pro*_*eur 0 python exception python-3.x
我在 Python 3.6 中遇到了一个有趣的现象。如果我self在__exit__类的方法中返回,似乎在with使用所述类的块中引发的任何异常都会消失。我不知道为什么会发生这种情况,而且这似乎不是理想的行为。使用以下代码,我可以重现它:
class SomeObject(object):
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
return self
if __name__ == '__main__':
with SomeObject():
print('This print statement works')
raise Exception('This exception is not raised for some reason')
print('This statement is printed as if nothing happened')
Run Code Online (Sandbox Code Playgroud)
这使我想到以下问题: