相关文章推荐
霸气的花卷  ·  python list 错位相减 ...·  2 月前    · 
憨厚的大脸猫  ·  python ...·  2 月前    · 
小猫猫  ·  python tornado ...·  2 月前    · 
有腹肌的充值卡  ·  pycharm console 清屏 ...·  1 月前    · 
爱看球的太阳  ·  Android ...·  1 年前    · 
豪气的青蛙  ·  如果用docker ...·  1 年前    · 

避免Python中的多个try except块

1 人关注

我想用 try excpept 块来处理一些函数调用。有什么更好更干净的方法吗。我目前的流程是

def handle_exception():
    except Exception:
        print("Failed to init module x")
    except Exception:
        print("Failed to init module y")
    except Exception:
        print("Failed to init module z")
    
python
exception
Pranjal Doshi
Pranjal Doshi
发布于 2021-07-07
1 个回答
Guy
Guy
发布于 2021-07-07
已采纳
0 人赞同

你可以在一个循环中调用这些模块

def handle_exception():
    modules = x, y, z
    for module in modules:
            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():