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.

    code a
except ExplicitException:

    code b
except ExplicitException:
        code c
    except ExplicitException:
            code d
        except ExplicitException:

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

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` 

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

        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:
            return f()
        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


Python try multiple times


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

Your email address will not be published. Required fields are marked *