Does 'finally' always execute in Python?

前端 未结 6 2067
眼角桃花
眼角桃花 2021-01-29 21:38

For any possible try-finally block in Python, is it guaranteed that the finally block will always be executed?

For example, let’s say I return while in an <

6条回答
  •  一整个雨季
    2021-01-29 22:18

    Well, yes and no.

    What is guaranteed is that Python will always try to execute the finally block. In the case where you return from the block or raise an uncaught exception, the finally block is executed just before actually returning or raising the exception.

    (what you could have controlled yourself by simply running the code in your question)

    The only case I can imagine where the finally block will not be executed is when the Python interpretor itself crashes for example inside C code or because of power outage.

提交回复
热议问题