Catching exception in context manager __enter__()

后端 未结 7 1677
栀梦
栀梦 2020-12-08 01:00

Is it possible to ensure the __exit__() method is called even if there is an exception in __enter__()?

>>> class TstCont         


        
7条回答
  •  一向
    一向 (楼主)
    2020-12-08 01:52

    No. If there is the chance that an exception could occur in __enter__() then you will need to catch it yourself and call a helper function that contains the cleanup code.

提交回复
热议问题