Python异常:对于任何异常调用相同的函数

7 投票
2 回答
2630 浏览
提问于 2025-04-15 11:18

注意下面的代码,如果抛出了任何异常,就会调用 foobar()。有没有办法在不在每个异常中都写同样一行代码的情况下实现这个功能呢?

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

2 个回答

12

你可以用一个字典来把异常和要调用的函数对应起来:

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() 
18
success = False
try:
    foo()
    success = True
except(A):
    bar()
except(B):
    baz()
except(C):
    bay()
finally:
    if not success:
        foobar()

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答