Search code examples
pythoncoding-stylenestedflat

How to try several methods with flat style?


If I want to try many way to avoid some error, I may write:

try:

    try:
        trial_1()
    except some_error:
        try:
            trial_2()
        except some_error:
            try:
                trial_3()
            ...
    print "finally pass"

except some_error:
    print "still fail"

But there are too many trials so too many nest, how to write it in a flat style?


Solution

  • You could do this:

    def trial1 (): 42 / 0
    def trial2 (): [] [42]
    def trial3 (): 'yoohoo!'
    def trial4 (): 'here be dragons'
    
    for t in [trial1, trial2, trial3, trial4]:
        print ('Trying {}.'.format (t.__name__) )
        try:
            t ()
            print ('Success')
            break
        except Exception as ex:
            print ('Failed due to {}'.format (ex) )
    else:
        print ('Epic fail!')
    

    Output is:

    Trying trial1.
    Failed due to division by zero
    Trying trial2.
    Failed due to list index out of range
    Trying trial3.
    Success