1

I want to handle few function calls using try excpept block. Is there any better and cleaner way to do it. My current flow is

def handle_exception():
    try:
        x()
    except Exception:
        print("Failed to init module x")
    try:
        y()
    except Exception:
        print("Failed to init module y")
    try:
        z()
    except Exception:
        print("Failed to init module z")

1 Answer 1

3

You can invoke the modules in a loop

def handle_exception():
    modules = x, y, z
    for module in modules:
        try:
            module()
        except Exception:
            print(f'Failed to init module {module.__name__}')

If you want to pass parameters as well you can use dict to store the data

def handle_exception():
    modules = {x: [1, 2], y: 'asd', z: 5}
    for module, params in modules.items():
        try:
            module(params)
        except Exception:
            print(f'Failed to init module {module.__name__}')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks... This will really work. Is there any way to pass parameters in this as well? That will really be helpful.
@PranjalDoshi There is, see updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.