为什么 finally 会执行,尽管我们在 except 块中继续执行,它将控制权转移到 while 的顶部?

Why does finally execute although we have continue in except block which transfers the control to the top of the while?

这是代码

while True:
   try: 
     age = int(input("Enter your age"))
   except ValueError:
     print("Enter the age in integer")
     continue
   except ZeroDivisionError:  #when trying to divide the age for an age groups
     print("Age cannot be zero")
     continue
   else:
     print("thank you!!")
     break
   finally:
     print("ok! I am finally done")

在输入中,对于 age,我给出了一个字符串(例如:wefervrsvr),因此它必须通过具有 print 函数的 except 块中的 ValueError,然后是 continue使程序控制在循环顶部的语句,因此它再次要求我们输入,但我在这里不明白的是,为什么 finally 在控制跳转到顶部尝试块之前执行,因为我在输出中看到。

来自python docs

When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed ‘on the way out'.

'on the way out' 基本上意味着,如果 continue 语句在异常子句中执行,则 finally 子句中的代码将被执行,然后循环将继续到下一次迭代。

finally 块的存在是为了保证您可以执行某些代码,而不管 try 块中发生了什么。 continue 关键字不会规避它,即使是未处理的异常也不会规避它。

例如,如果您删除了 ValueError 的捕获,您仍然会命中 finally 块:

try:
    raise ValueError("unhandled exception type");
except ZeroDivisionError:
    print("problems.")
finally:
    print("will print, even in the face of an unhandled exception")

一个不错的答案

import time;
while True:
    try:
        print("waiting for 10 seconds...\n")
        continue
        print("never show this")
    finally:
        print("Finally starts executing\n");
        time.sleep(10)
        print("\nFinally ends executing control jumps to start of the loop");