Why is break allowed in finally, but continue is not?
Ben Finney
ben+python at benfinney.id.au
Sun Dec 13 17:27:50 EST 2015
Ned Batchelder <ned at nedbatchelder.com> writes:
> For testing coverage.py, I wrote a program to generate
> randomly-structured Python functions. When compiling
> the results, I got a message I'd never seen before:
>
> SyntaxError: 'continue' not supported inside 'finally' clause
>
> I guess this makes sense, when cleaning up from an
> exception, continuing the loop seems an odd thing to do.
> But 'break' is allowed in 'finally' clauses! I tried this:
>
> # Huh? This prints "here", and no exception is raised.
>
> for i in range(1):
> try:
> 1/0
> finally:
> # If you change this to "continue", you get:
> # 'continue' not supported inside 'finally' clause
> break
> print "here"
>
> The finally is perfectly willing to have a 'break', but it's
> a syntax error to have 'continue'? Why? I don't see a
> difference between the two when it comes to cleaning up
> exceptions.
Raymond Hettinger's answer is:
The use of continue in a finally-clause is forbidden because its
interpretation would have been problematic. […]
<URL:https://stackoverflow.com/questions/8302293/why-is-continue-not-allowed-in-a-finally-clause-in-python#answer-8302601>
The example he uses::
for i in range(10):
print i
try:
raise RuntimeError
finally:
continue # if the loop continues, what would happen to the exception?
print i
What, in your opinion, should the above code do if instead of ‘continue’
some other flow-control statement is used?
> There are other things you can do in a finally clause that
> will prevent the exception from being raised, like 'return',
> and 'break' works just fine.
Hettinger doesn't defend those, and is dubious about ‘return’'s
candidacy:
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 ;-)
> So why treat 'continue' specially?
I am inclined to agree, but in the opposite direction: a case should be
made for allowing *any* flow-control statement in an exception-handler's
‘finally’ clause.
--
\ “We can't depend for the long run on distinguishing one |
`\ bitstream from another in order to figure out which rules |
_o__) apply.” —Eben Moglen, _Anarchism Triumphant_, 1999 |
Ben Finney
More information about the Python-list
mailing list