Python:在异常时继续for循环的迭代

20 投票
1 回答
48096 浏览
提问于 2025-04-17 07:12

我在Python里写了一个简单的for循环,但它在遇到错误时就退出了,尽管我在处理错误的地方加了continue。当它遇到IndexError时,还有大约10行代码没执行完,但循环却提前结束了。我是不是漏掉了什么?

for row in hkx:  ##'hkx' are rows being read in from 'csv.open'
    try:
        print row[2],row[4]
    except IndexError, e:
        print 'Error:',e
        print 'Row Data:',len(row),row
        continue  ## I thought this would just move on to the next row in 'hkx' 

(抱歉,我是Python的新手…) 感谢你的帮助!

1 个回答

12

这个代码的运行方式是正确的,它会继续执行下一行。如果你的代码因为异常而提前结束,那可能不是因为索引错误(IndexError),或者这个错误是从 try: 块外面的代码抛出来的。

>>> hkx = [ range(5), range(4), range(4), range(5) ]
>>> for row in hkx:  ##'hkx' are rows being read in from 'csv.open'
    try:
        print row[2],row[4]
    except IndexError, e:
        print 'Error:',e
        print 'Row Data:',len(row),row
        continue  ## I thought this would just move on to the next row in 'hkx'

2 4
2 Error: list index out of range
Row Data: 4 [0, 1, 2, 3]
2 Error: list index out of range
Row Data: 4 [0, 1, 2, 3]
2 4
>>> 

注意,如果这一行至少有3个项目,你的输出会只显示一半。如果你使用格式化字符串,就可以避免这个问题。(比如说 print "{} {}".format(row[2],row[4])

你没有说明 hkx 是怎么定义的,只说它来自 csv.open。如果 hkx 是一个生成器,而不是简单的列表,那么在遍历它的时候可能会抛出索引错误。在这种情况下,你不会捕捉到这个错误,但错误信息会显示出 for row in hkx 这一行。

撰写回答