Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python exceptions: call same function for any Exception

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()
like image 253
Jason Coon Avatar asked Apr 28 '09 18:04

Jason Coon


2 Answers

success = False
try:
    foo()
    success = True
except(A):
    bar()
except(B):
    baz()
except(C):
    bay()
finally:
    if not success:
        foobar()
like image 191
FogleBird Avatar answered Oct 25 '22 20:10

FogleBird


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() 
like image 40
Jochen Ritzel Avatar answered Oct 25 '22 20:10

Jochen Ritzel