33

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?

Andres Riofrio
  • 9,851
  • 7
  • 40
  • 60
  • 12
    @AndrewG., the point of asking the question was so that this information be more easily find-able. It took me a few minutes to come up with that example. :) – Andres Riofrio May 11 '12 at 03:18

3 Answers3

40

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

Joel Cornett
  • 24,192
  • 9
  • 66
  • 88
  • 9
    [As of Python 3.8](https://docs.python.org/dev/whatsnew/3.8.html#other-language-changes) continue statements are legal within the finally clause. – Carter Jan 04 '19 at 18:17
5

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=0
while 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=0
i=1
i=2
i=4
'''
Ross Gibson
  • 79
  • 1
  • 3
1

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

Ronit Roy
  • 11
  • 1
  • 1
    Welcome to stackoverflow. It's always best to post code as text, not as images. Others can then copy/paste to try it. Highlight the code and press Ctrl+k or highlight and click the '{}' symbol in the answer box. – Tls Chris Jul 23 '20 at 16:34