Python异常:对任何异常调用相同的函数
请注意,在下面的代码中,如果引发任何异常,将调用Python异常:对任何异常调用相同的函数,python,exception,Python,Exception,请注意,在下面的代码中,如果引发任何异常,将调用foobar()。有没有一种方法可以做到这一点,而不必在每个异常中使用相同的行 try: foo() except(ErrorTypeA): bar() foobar() except(ErrorTypeB): baz() foobar() except(SwineFlu): print 'You have caught Swine Flu!' foobar() except: foobar() 您可以使用字典将异
foobar()
。有没有一种方法可以做到这一点,而不必在每个异常中使用相同的行
try:
foo()
except(ErrorTypeA):
bar()
foobar()
except(ErrorTypeB):
baz()
foobar()
except(SwineFlu):
print 'You have caught Swine Flu!'
foobar()
except:
foobar()
您可以使用字典将异常映射到要调用的函数:
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()
如果抛出无异常,则将执行Finally。+1不知道
raise
无异常会重新引发异常
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()