python继续循环,Python:在异常上继续for循环的迭代

I have a simple for loop in Python that is exiting on exceptions even though the exception block contains a continue. There are still about 10 lines left to read when it hits an IndexError and exits the for loop. What am I missing here?

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'

(sorry, total Python newbie here…)

Thanks in advance!

解决方案

It does exactly as it should and continues with the next line. If an exception is terminating your code early then it must either not be IndexError, or it must be being thrown from some code outside the try: block.

>>> 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

>>>

Note that if the row contains at least 3 items you'll get half of your printout, if you use a format string you can avoid that. (e.g. print "{} {}".format(row[2],row[4]))

You haven't said how hkx is defined except that it comes from csv.open. If it is a generator rather than a simple list then it might be that simply iterating over it throws IndexError. In that case you wouldn't catch that but the stack dump would show the line with the for row in hkx.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值