Exceptions for Python: calling the same function for any exception

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

 try: foo() except(ErrorTypeA): bar() foobar() except(ErrorTypeB): baz() foobar() except(SwineFlu): print 'You have caught Swine Flu!' foobar() except: foobar() 
+4
source share
2 answers
 success = False try: foo() success = True except(A): bar() except(B): baz() except(C): bay() finally: if not success: foobar() 
+15
source

You can use a dictionary to map exceptions to 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() 
+11
source

All Articles