Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: continue iteration of for loop on exception

Tags:

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!

like image 309
Nathan Avatar asked Nov 28 '11 08:11

Nathan


1 Answers

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.

like image 156
Duncan Avatar answered Sep 17 '22 13:09

Duncan