避免 python 中的多次尝试除外块

Avoid multiple try except block in python

我想使用 try excpept 块处理几个函数调用。有没有更好更清洁的方法来做到这一点。我目前的流量是

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

您可以循环调用模块

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

如果你也想传递参数你可以使用dict来存储数据

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