views:

286

answers:

2

Notice in the code below that foobar() is called if any Exception is thrown. Is there a way to do this without using the same line in every Exception?

try:
  foo()
except(ErrorTypeA):
  bar()
  foobar()
except(ErrorTypeB):
  baz()
  foobar()
except(SwineFlu):
  print 'You have caught Swine Flu!'
  foobar()
except:
  foobar()
+13  A: 
success = False
try:
    foo()
    success = True
except(A):
    bar()
except(B):
    baz()
except(C):
    bay()
finally:
    if not success:
        foobar()
FogleBird
+10  A: 

You can use a dictionary to map exceptions against functions to call:

exception_map = { ErrorTypeA : bar, ErrorTypeB : baz }
try:
    try:
        somthing()
    except tuple(exception_map), e: # this catches only the exceptions in the map
        exception_map[type(e)]() # calls the related function
        raise # raise the Excetion again and the next line catches it
except Exception, e: # every Exception ends here
    foobar()
THC4k
+1 didn't know that `raise` with no exceptions re-raises the exception
Nathan Fellman
Very cool idea.
George
+1 Very nice idea! @ Nathan: me too
rubik