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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With