Python:在异常上继续for循环的迭代 [英] Python: continue iteration of for loop on exception

查看:629
本文介绍了Python:在异常上继续for循环的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中有一个简单的 for 循环,即使异常块包含 continue ,该循环也会在异常时退出。当它遇到 IndexError 并退出 for 循环时,仍有大约10行需要读取。我在这里想念什么?

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' 

(很抱歉,这里的Python新手总数…)
预先感谢!

(sorry, total Python newbie here…) Thanks in advance!

推荐答案

它完全按照应有的方式运行,并继续下一行。如果异常提前终止您的代码,则该异常要么不能为IndexError,要么必须从 try:块之外的某些代码中抛出。

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

请注意,如果该行至少包含3个项目,则您将获得一半的打印输出使用格式字符串可以避免这种情况。 (例如 print {} {}。format(row [2],row [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]))

您没有说过hkx的定义方式,只是它来自 csv.open 。如果它是一个生成器而不是一个简单的列表,则可能仅仅是对其进行迭代会引发IndexError。在那种情况下,您不会捕获到该信息,但是堆栈转储将显示带有 for hkx行的行

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.

这篇关于Python:在异常上继续for循环的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆