Python: Using continue in a try-finally statement in a loop

Andres Riofrio picture Andres Riofrio · May 11, 2012 · Viewed 12.4k times · Source

Will the following code:

while True:
    try:
        print("waiting for 10 seconds...")
        continue
        print("never show this")
    finally:
        time.sleep(10)

Always print the message "waiting for 10 seconds...", sleep for 10 seconds, and do it again? In other words, do statements in finally clauses run even when the loop is continue-ed?

Answer

Joel Cornett picture Joel Cornett · May 11, 2012

From the 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.’ A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation — this restriction may be lifted in the future).