2009-04-28 6 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

+0

例外がスローされない場合は、最後に実行されます。 –

答えて

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

+1は例外なしで 'raise'が例外を再発生することを知らなかった –

+0

非常にクールなアイデア。 –

+0

+1とても良いアイデア! @ネイサン:私も – rubik

関連する問題