Conditional except: blocks

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Robert Brewer

    Conditional except: blocks

    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(arg s)
    except (None, Exception)[self.trapErrors], exc:
    if page == u'-Error':
    raise exc
    else:
    return self.handle_err or(exc, scriptWithPath)

    If self.trapErrors is True, all exceptions (which subclass Exception)
    get trapped, otherwise, no exceptions are trapped. Spiffy. :)


    FuManChu

  • Aahz

    #2
    Re: Conditional except: blocks

    In article <mailman.27.107 3065446.12720.p ython-list@python.org >,
    Robert Brewer <fumanchu@amor. org> wrote:[color=blue]
    >
    >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(arg s)
    >except (None, Exception)[self.trapErrors], exc:
    > if page =3D=3D u'-Error':
    > raise exc
    > else:
    > return self.handle_err or(exc, scriptWithPath)
    >
    >If self.trapErrors is True, all exceptions (which subclass Exception)
    >get trapped, otherwise, no exceptions are trapped. Spiffy. :)[/color]

    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(arg s)
    except exceptTuple, exc:
    # Handle exception
    --
    Aahz (aahz@pythoncra ft.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.

    Comment

    • sdd

      #3
      Re: Conditional except: blocks

      Robert Brewer wrote:[color=blue]
      > try:
      > return nextHandler(arg s)
      > except (None, Exception)[self.trapErrors], exc:
      > if page == u'-Error':
      > raise exc[/color]
      raise # re-raises the same error with the full traceback.[color=blue]
      > else:
      > return self.handle_err or(exc, scriptWithPath)[/color]

      Comment

      Working...