The possibility of getting an exception raised and then just swallowed because you're using a continue
is a strong argument, but the exception is also swallowed when you use a break
or return
instead.
For example, this works and the exception is swallowed:
for i in range(10):
print i
try:
raise Exception
finally:
break
print i # not gonna happen
This again works with no error (when in a function) and the exception is swallowed too:
for i in range(10):
print i
try:
raise Exception
finally:
return
print i # not gonna happen
So why would break
and return
be allowed in a finally
block, with or without possible raised errors, but continue
not?
You might also consider the combination of the following factors in the issue:
finally
is always executed;
continue
"aborts" the current iteration.
This will mean that inside each loop, because of the finally
always executing, you will always have a continue
witch basically
says "abort current iteration", "abort current iteration", "abort current iteration" ... witch doesn't really make any sense. But it doesn't make sense either to use break
and return
. The current iteration is also aborted with the only difference
that you now end up with just one iteration.
So the question "Why is continue
not allowed in a finally
?" can also be asked as "Why is break
and return
allowed?".
Maybe because it made sense not to at that point? It was the developers decision and now its like it is? Sure, it might also be implementor's laziness but who knows, maybe they had something in mind and perhaps, in another version of Python, it would make more
sense to have it another way?
The idea is that the examples here are just extreme. You don't just write code like that, do you? There is sure to be some
logic in the finally
block to say when to break/return/continue
, whatever, and not just have it blunt like that. As such, IMHO continue
inside a finally
should be allowed because I would appreciate writing a clean code with using continue
in finally
if that's what I need, instead of resorting to a code workaround for this limitation (i.e. in Python's philosophy "We're all consenting adults here").
continue
in a finally block, and various issues that may come up. Worth the read. – Prehuman