Elegant alternative to long exception chains?

  • A+
Category:Languages

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.


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: