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

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


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).


The documentation uses slightly unclear language ("on the way out") to explain how this scenario plays out. If a continue statement is executed inside of an exception clause, the code in the finally clause will be executed and then the loop will continue on to the next iteration.

Here's a very clear example that demonstrates the behavior.

Code:

i=0while i<5:    try:        assert(i!=3) #Raises an AssertionError if i==3        print("i={0}".format(i))    except:        continue    finally:        i+= 1; #Increment i'''Output:i=0i=1i=2i=4'''


Now from the latest version of python (3.8.4) , 'continue' can be used inside 'finally' blocks.enter image description here