我想知道在python 中编写try
.. except
语句最优雅的方式是什么.假设我有这个代码:
with open(sys.argv[1]) as f: for line in f: try: do_1(line) except: pass try: do_2(line) except: pass try: do_3(line) except: pass ... ...
写这个的最好方法是什么?我的行为是顺序的.但是,如果do_1
失败,我仍然想要表演do_2
.如果所有这些都在一个try
.. except
块中,那么如果do_1
失败,我永远不会到达do_2
.这是正确的方式,还是我可以except
为所有d0_i
行动都有一个?
把它写成循环很简单:
for action in [do_1, do_2, do_3, ...]: try: action(line) except AppropriateExceptionType: pass
我会考虑你的try/except
陈述的公共代码.就像是:
def run_safely(f, *args): try: f(*args) except SpecificException: # handle appropriately here pass with open(sys.argv[1]) as f: for line in f: run_safely(do_1, line) run_safely(do_2, line) run_safely(do_3, line)