2009-04-28 4 views
4

Remarquez dans le code ci-dessous que foobar() est appelée si une exception est levée. Y at-il un moyen de faire cela sans utiliser la même ligne dans chaque exception?Exceptions Python: appelez la même fonction pour toute exception

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

recherchez-vous enfin? – SilentGhost

+0

Enfin sera exécuté si aucune exception n'est levée. –

Répondre

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

Vous pouvez utiliser un dictionnaire pour mapper des exceptions contre les fonctions d'appel:

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 ne savait pas que «raise» sans exception re-soulève l'exception –

+0

Très bonne idée. –

+0

+1 Très bonne idée! @ Nathan: moi aussi – rubik

Questions connexes