2013-04-21 126 views
0

繼續從以前的真棒幫助,我現在有異常處理的問題。 我有11個地塊的索引號被選中。如果用戶選擇高於11,它應該請求他們重新輸入但atm,我得到IndexError:列表索引超出範圍。 我會認爲除了行會處理其他任何東西......但它必須是一個缺失的行?IndexError ...超出範圍,

try: 
    response = raw_input("Select a monitoring plot from the list (0-11): ") 
    if response == 'q': 
     confirm = raw_input('Confirm quit (y/ n)...') 
      if confirm == 'y': 
       print 'Bye' 
       break 
      else: 
       continue 
    selected = dataList[int(plotSelect) + 1] 
    print 'You selected : ', selected[1] 
except ValueError: 
    print "Error: Please enter a number between 0 and 11" 
+0

那是什麼'plotSelect'?它應該是'response'? – Cairnarvon 2013-04-21 03:37:36

回答

4

except ValueError only only a ValueError。您需要添加IndexError還有:

except (ValueError, IndexError): 
+0

是的,就是這樣。愚蠢的我......謝謝 – 2013-04-21 04:12:28

0

except ValueError意味着你只能望塵莫及類型ValueError的execptions。如果您想要以不同的方式處理它,或者抓住兩者並以相同的方式處理,請包含IndexError的捕獲物。

0

ValueError將拿出當他用戶輸入的東西是不是數字。 (所以int("hello")拋出ValueError

IndexError當用戶輸入的數字大於列表中的元素數時拋出。 (例如,range(5)[7]

你可能想嘗試讓你先輸入一個循環像下面

resp = "" 
while resp not in ('0', '1', ... '10', 'q'): 
    resp = raw_input(...)