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()
                success = False
try:
    foo()
    success = True
except(A):
    bar()
except(B):
    baz()
except(C):
    bay()
finally:
    if not success:
        foobar()
                        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() 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With