The following code raises a syntax error:
>>> for i in range(10):
... print i
... try:
... pass
... finally:
... continue
... print i
...
File "<stdin>", line 6
SyntaxError: 'continue' not supported inside 'finally' clause
Why isn’t a continue statement allowed inside a finally clause?
P.S. This other code on the other hand has no issues:
>>> for i in range(10):
... print i
... try:
... pass
... finally:
... break
...
0
If it matters, I’m using Python 2.6.6.
The use of continue in a finally-clause is forbidden because its interpretation would have been problematic. What would you do if the finally-clause were being executed because of an exception?
It is possible for us to make a decision about what this code should do, perhaps swallowing the exception; but good language design suggests otherwise. If the code confuses readers or if there is a clearer way to express the intended logic (perhaps with
try: ... except Exception: pass; continue), then there is some advantage to leaving this as a SyntaxError.Interestingly, you can put a return inside a finally-clause and it will swallow all exceptions including KeyboardInterrupt, SystemExit, and MemoryError. That probably isn’t a good idea either 😉