[英]How to handle error in a for loop (python) and continue execution
我试图让我的脚本仍然打印动作 2“print (list1[3])”并跳过动作 1“print (list1[9])”,如果它不能执行它。 如果我的问题不够清楚,我会提前通知我,我会尽力解释这个问题。 我是初学者。
list1 = ['a','b','c','d','f']
try:
for i in list1:
#action 1
print (list1[9])
#action 2
print (list1[3])
break
except:
pass
只需尝试每个动作,而不是同时尝试两个动作,就像这样
list1 = ['a','b','c','d','f']
for i in list1:
try:
#action 1
print (list1[9])
except IndexError:
pass
try:
#action 2
print (list1[3])
except IndexError:
pass
break
尝试这种更清洁的方式
l = ['a','b','c','d','f']
# execute the function in try-except
def try_to_do(fun, index):
try:
fun(l[index])
except:
pass
for j in l:
try_to_do(print, 11)
try_to_do(print, 1)
print('Done')
在循环内使用 try except
list1 = ['a','b','c','d','f']
for i in list1:
try:
#action 1
print (list1[9])
except:
print(e.with_traceback())
try:
#action 2
print (list1[3])
except Exception as e:
print(e.with_traceback())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.