2009-04-28 72 views
4

请注意,如果抛出任何异常,将调用foobar()。有没有办法做到这一点,而不是在每个异常中使用相同的行?Python异常:针对任何异常调用相同的函数

try: 
    foo() 
except(ErrorTypeA): 
    bar() 
    foobar() 
except(ErrorTypeB): 
    baz() 
    foobar() 
except(SwineFlu): 
    print 'You have caught Swine Flu!' 
    foobar() 
except: 
    foobar() 
+0

你在找最后? – SilentGhost 2009-04-28 18:40:47

+0

如果没有例外被抛出,最后将被执行。 – 2009-04-28 18:52:35

回答

15
success = False 
try: 
    foo() 
    success = True 
except(A): 
    bar() 
except(B): 
    baz() 
except(C): 
    bay() 
finally: 
    if not success: 
     foobar() 
11

您可以使用字典来映射针对功能异常调用:

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