Conditional except: blocks

Aahz aahz at pythoncraft.com
Fri Jan 2 14:11:52 EST 2004


In article <mailman.27.1073065446.12720.python-list at python.org>,
Robert Brewer <fumanchu at amor.org> wrote:
>
>I don't have a quesiton or problem, I just figured some of you would
>enjoy the somewhat bizarre logic of the snippet I just wrote for a CGI
>request dispatcher:
>
>try:
>    return nextHandler(args)
>except (None, Exception)[self.trapErrors], exc:
>    if page =3D=3D u'-Error':
>        raise exc
>    else:
>        return self.handle_error(exc, scriptWithPath)
>
>If self.trapErrors is True, all exceptions (which subclass Exception)
>get trapped, otherwise, no exceptions are trapped. Spiffy. :)

That's pretty sick.  If you really need to do that, here's a more
Pythonic approach:

    # This goes at beginning of program
    # or maybe at class/instance initialization
    if trapErrors:
        exceptTuple = (Exception,)
    else:
        exceptTuple = (None,)

    # some time later
    try:
        return nextHandler(args)
    except exceptTuple, exc:
        # Handle exception
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.



More information about the Python-list mailing list