请注意,在下面的代码中,如果抛出任何异常,则会调用foobar()
。有没有办法在不使用每个Exception中的相同行的情况下执行此操作?
try:
foo()
except(ErrorTypeA):
bar()
foobar()
except(ErrorTypeB):
baz()
foobar()
except(SwineFlu):
print 'You have caught Swine Flu!'
foobar()
except:
foobar()
答案 0 :(得分:15)
success = False
try:
foo()
success = True
except(A):
bar()
except(B):
baz()
except(C):
bay()
finally:
if not success:
foobar()
答案 1 :(得分: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()