Python: Correct way to handle chain exceptions

The Dan

I would like to look for a better way to handle the following exception,

def fun(i, j, k, l):
    try:
        do_something_1(i)
    except TimeoutException as f:
        try:
            do_something_2(j)
        except TimeoutExeption as e:
            try:
                do_something_3(k)
            except TimeoutExeption as e:
                try:
                    do_something_4(l)
                except TimeoutExeption as e:
                    raise Exception

The basic idea is to try something, if it doesn't work, try next thing and so on until it gets what it wants or fails. But it has to follow the order of execution.

How can I make it better?

sabik

Probably use a loop?

def fun(i):
    errors = []
    things_to_try = (thing1, thing2, thing3, thing4)
    for thing in things_to_try:
        try:
            thing(i)
        except Exception as e:
            errors.append(e)
        else:
            break
    else:
        raise Exception("Failed: %s" % errors)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Correct way to handle exceptions in Java

The correct way to handle Exceptions in a Python2.7 context manager class

Correct way to handle exceptions in Spring Boot

Is there a way to handle exceptions automatically with Python Click?

How to handle Python exceptions in a decent way?

Recommended way to handle exceptions?

What is a good way to handle exceptions when trying to read a file in python?

What is the correct way python memory management in case of exceptions?

Is this correct way to handle an exception?

AngularJS : Is this the correct way to chain promises?

What is the cleanest/correct way to handle Future.get() custom exceptions inside callable? (Advanced)

What is the correct way to handle exceptions in a REST API that produces an Excel or PDF file as response?

Rails way to catch and handle exceptions

What is preferable way to handle exceptions?

What is the cleaner way to handle exceptions

Correct way of throwing exceptions with Reactor

Correct way to handle exception handshake between python and oracle

Correct way to handle deprecated API

Correct way to handle deadlocks in Hibernate

How to handle exceptions in a nested method chain and revert changes in intermediate method?

does merry handle exceptions in python?

Handle Python Exceptions like in JS

Preferred way to handle Java exceptions in ServletContextListener

Best way to handle exceptions that can not occur

Proper way to handle exceptions in Ruby on Rails

What is the best way to handle exceptions in this scenario

Correct way to document bubbled exceptions in C#?

Whats the correct Go way to do handle errors

Correct way to handle incorrect URL when opening