Python – How to Write Multiple Try Statements in One Block

exceptionpython

I want to do:

try:
    do()
except:
    do2()
except:
    do3()
except:
    do4()

If do() fails, execute do2(), if do2() fails too, exceute do3() and so on.

best Regards

Best Answer

If you really don't care about the exceptions, you could loop over cases until you succeed:

for fn in (do, do2, do3, do4):
    try:
        fn()
        break
    except:
        continue

This at least avoids having to indent once for every case. If the different functions need different arguments you can use functools.partial to 'prime' them before the loop.

Related Question