[Python-ideas] syntax to continue into the next subsequent except block
Terry Reedy
tjreedy at udel.edu
Fri Sep 14 01:46:05 CEST 2012
On 9/13/2012 5:05 PM, Paul Wiseman wrote:
> I think it would be useful if there was a way to skip into the next
> except block, perhaps with continue as I think it's currently always
> illegal to use in an except block. I don't believe there's currently a
> way to do this.
>
> This is my reasoning, often there's multiple reasons for exceptions that
> raise the same exception, as an example an IOError might get raised for
> lots of different reasons. If you want to handle one or several of these
> reasons, you have to catch all exceptions of this type, but there's not
> really a way to "put back" the exception if it isn't the type you were
> after. For instance
>
> try:
> operation()
> except IOError as err:
> if err.errno == 2:
> do_something()
> else:
> continue #This would continue the except down to the next
> check, except Exception
> except Exception as err:
> logger.error("Error performing operation: {}".format(err.message)")
> some_clean_up()
> raise
> The current alternatives to get this behaviour I don't believe are as
> nice, but maybe I'm missing something
As you already know, raise puts the exception back, in a sense
try:
try:
operation()
except IOError as err:
if err.errno == 2:
do_something()
else:
raise
except Exception as err:
logger.error("Error performing operation: {}".format(err.message)")
some_clean_up()
raise
or probably better
try:
operation()
except Exception as err:
if isinstance(err, IOError) and err.errno == 2:
do_something()
else:
logger.error("Error performing operation: {}".format(err.message)")
some_clean_up()
raise
--
Terry Jan Reedy
More information about the Python-ideas
mailing list