Does 'finally' always execute in Python?

前端 未结 6 2180
眼角桃花
眼角桃花 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:26

    According to the Python documentation:

    No matter what happened previously, the final-block is executed once the code block is complete and any raised exceptions handled. Even if there's an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run.

    It should also be noted that if there are multiple return statements, including one in the finally block, then the finally block return is the only one that will execute.

提交回复
热议问题