Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant alternative to long exception chains? [duplicate]

Tags:

python

A lot of times I find myself writing something that looks like this:

try:
    procedure_a()
except WrongProcedureError:
    try:
        procedure_b()
    except WrongProcedureError:
        try:
            procedure_c()
        except WrongProcedureError:
            give_up()

This is hideous. Is there a more elegant way to implement this kind of "try things until one doesn't exception" logic? It seems like this is the kind of thing that would come up a lot; I'm hoping there's some language feature I don't know about that's designed for this exact thing.

like image 323
Schilcote Avatar asked Apr 20 '18 18:04

Schilcote


1 Answers

You can use a for/else construct for this:

for proc in [procedure_a, procedure_b, procedure_c]:
    try:
        proc()
    except WrongProcedureError:
        continue
    else:
        break
else:
    give_up()

The else clause of the for loop triggers only when control falls off the bottom of the for clause naturally. If you break out (as you will if any of the three procedures do not throw an exception), it won't trigger.

like image 161
Adam Smith Avatar answered Sep 23 '22 15:09

Adam Smith