Pranjal Doshi
Pranjal Doshi

Reputation: 1262

Avoid multiple try except block in python

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")

Upvotes: 1

Views: 124

Answers (1)

Guy
Guy

Reputation: 50809

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__}')

Upvotes: 3

Related Questions