Skip to content

Python try multiple times

  • by

You can’t use try block multiple times in Python. You have to have to make this separate try blocks.

try:
    code a
except ExplicitException:
    pass

try:
    code b
except ExplicitException:
    try:
        code c
    except ExplicitException:
        try:
            code d
        except ExplicitException:
            pass

You can use fuckit module.
Wrap your code in a function with @fuckit decorator:

@fuckit
def func():
    code a
    code b #if b fails, it should ignore, and go to c.
    code c #if c fails, go to d
    code d

Python try multiple times

Simple example code multiple try statements in one block in Python.

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

Output:

Python try multiple times

Source: https://stackoverflow.com/questions/13874666

Do comment if you have any doubts or suggestions on this Python try block topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading