7

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()
1
  • Finally will be executed if an no exceptions are thrown. Commented Apr 28, 2009 at 18:52

2 Answers 2

18
success = False
try:
    foo()
    success = True
except(A):
    bar()
except(B):
    baz()
except(C):
    bay()
finally:
    if not success:
        foobar()
Sign up to request clarification or add additional context in comments.

Comments

12

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() 

1 Comment

+1 didn't know that raise with no exceptions re-raises the exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.