2009-04-28 9 views
4

Hinweis im folgenden Code wird foobar() aufgerufen, wenn eine Exception ausgelöst wird. Gibt es eine Möglichkeit, dies zu tun, ohne die gleiche Zeile in jeder Ausnahme zu verwenden?Python-Ausnahmen: Aufruf der gleichen Funktion für jede Exception

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

suchen Sie endlich? – SilentGhost

+0

Schließlich wird ausgeführt, wenn keine Ausnahmen ausgelöst werden. –

Antwort

15
success = False 
try: 
    foo() 
    success = True 
except(A): 
    bar() 
except(B): 
    baz() 
except(C): 
    bay() 
finally: 
    if not success: 
     foobar() 
11

können Sie ein Wörterbuch verwenden Ausnahmen gegen Funktionen zur Karte zu nennen:

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 wusste nicht, dass "Raise" ohne Ausnahmen die Ausnahme wieder erhöht –

+0

Sehr coole Idee. –

+0

+1 Sehr schöne Idee! @ Nathan: Ich auch – rubik

Verwandte Themen