[英]Python: continue iteration of for loop on exception
我在Python中有一個簡單的for
循環,即使異常塊包含一個continue
,也會在異常中退出。 當它遇到IndexError
並退出for
循環時,仍有大約10行要讀取。 我在這里錯過了什么?
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新手......)提前致謝!
它完全按照預期進行,並繼續下一行。 如果異常提前終止代碼,則它必須不是IndexError,或者必須從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])
)
你還沒有說過如何定義hkx,除了它來自csv.open
。 如果它是一個生成器而不是一個簡單的列表,那么它可能只是迭代它拋出IndexError。 在這種情況下,您不會捕獲,但堆棧轉儲將顯示for row in hkx
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.