相关文章推荐
乐观的竹笋  ·  如何快速上手MuJoCo ...·  1 月前    · 
着急的跑步鞋  ·  Python ...·  1 月前    · 
年轻有为的海龟  ·  使用Python ...·  1 月前    · 
幸福的墨镜  ·  macbook python ...·  1 月前    · 
欢快的冰淇淋  ·  vs2013 ...·  2 年前    · 

避免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():