Python: continue iteration of for loop on exception

后端 未结 1 1840
孤街浪徒
孤街浪徒 2021-02-12 15:42

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 le

相关标签:
1条回答
  • 2021-02-12 16:32

    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)
提交回复
热议问题