Conditional except: blocks

R

Robert Brewer

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 == 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. :)


FuManChu
 
A

Aahz

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
 
S

sdd

Robert said:
try:
return nextHandler(args)
except (None, Exception)[self.trapErrors], exc:
if page == u'-Error':
raise exc
raise # re-raises the same error with the full traceback.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top