[Python-ideas] syntax to continue into the next subsequent except block

Paul Wiseman poalman at gmail.com
Thu Sep 13 23:05:22 CEST 2012


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

This works but clearly not as nice with nested try excepts,
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

This is clearly a not very good and un-dry solution:
try:
    operation()
except IOError as err:
    if err.errno == 2:
        do_something()
    else:
        logger.error("Error performing operation: {}".format(err.message))
        some_clean_up()
        raise
except Exception as err:
    logger.error("Error performing operation: {}".format(err.message))
    some_clean_up()
    raise

There's the option of using a context manager, but personally I don't think
it's as explicit or as obvious as a try except block, but maybe others
would disagree
class SpecificCaseErrorHandler(object):
    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, tb):
        if exc_type is not None:
            if exc_type is IOError and exc_value.errno == 2:
                do_something()
                return True
                  logger.error("Error performing operation:
{}".format(err.message))
            some_clean_up()

with SpecificCaseErrorHandler():
    operation()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120913/c87a5993/attachment.html>


More information about the Python-ideas mailing list