Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write multiple try statements in one block in python?

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

like image 480
alwbtc Avatar asked Dec 14 '12 07:12

alwbtc


People also ask

Can you do multiple try statements in Python?

It is possible to have multiple except blocks for one try block. Let us see Python multiple exception handling examples. When the interpreter encounters an exception, it checks the except blocks associated with that try block. These except blocks may declare what kind of exceptions they handle.

Can we write more than 1 catch Bolcks with 1 try block?

Yes, we can define one try block with multiple catch blocks in Java.

What is nested try block in Python?

Nested try block is a block in which we can implement one try catch block into another try catch block. The requirement of nested try-catch block arises when an exception occurs in the inner try-catch block is not handled by the inner catch blocks then the outer try-catch blocks are checked for that exception.

Is there a try catch block in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.


2 Answers

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.

like image 171
Fredrik Håård Avatar answered Sep 25 '22 09:09

Fredrik Håård


I'd write a quick wrapper function first() for this.

usage: value = first([f1, f2, f3, ..., fn], default='All failed')

#!/usr/bin/env


def first(flist, default=None):

    """ Try each function in `flist` until one does not throw an exception, and
    return the return value of that function. If all functions throw exceptions,
    return `default` 

    Args: 
        flist - list of functions to try
        default - value to return if all functions fail

    Returns:
        return value of first function that does not throw exception, or
        `default` if all throw exceptions.

    TODO: Also accept a list of (f, (exceptions)) tuples, where f is the
    function as above and (exceptions) is a tuple of exceptions that f should
    expect. This allows you to still re-raise unexpected exceptions.
    """

    for f in flist:
        try:
            return f()
        except:
            continue
    else:
        return default

# Testing.

def f():
    raise TypeError

def g():
    raise IndexError

def h():
    return 1


# We skip two exception-throwing functions and return value of the last.
assert first([f, g, h]) == 1

assert first([f, g, f], default='monty') == 'monty'
like image 32
Kenan Banks Avatar answered Sep 23 '22 09:09

Kenan Banks