2009-04-28 73 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()