[Python-ideas] Possible PEP regarding the use of the continue keyword in try/except blocks
Steven D'Aprano
steve at pearwood.info
Sun Jan 6 00:31:34 EST 2019
On Sun, Jan 06, 2019 at 01:38:33AM +0100, Simon wrote:
> I propose to be able to use the continue keyword to continue the execution
> of the try block even when an error is handled. The above could then be
> changed to :
>
>
> try:
> i = int("string")
> print("continued on")
> j = int(9.0)
> except ValueError as e:
> print(e)
> continue
>
> >>> "invalid literal for int() with base 10: 'string'"
> >>> "continued on"
That's literally what the except clause is intended for, not the body of
the try block.
try:
i = int("string")
except ValueError as e:
print(e)
print("continued on")
j = int(9.0)
Putting the error handler in the try block is a serious problem for two
reasons:
(1) What if an error *doesn't* occur? The error handler occurs anyway:
try:
i = int("1234") # This succeeds.
# and then immediately runs the error handler... oops!
print("continued on")
j = int(9.0)
except ValueError as e:
print(e)
continue
(2) And what happens if the error handler raises an error? The exception
is raised, the except clause is called, the continue statement jumps
back to the same block of code that just failed and will fail again. And
again. And again. Forever.
--
Steve
More information about the Python-ideas
mailing list