Reputation: 81
Following on from the awesome help from earlier, I now have an issue with exception handling. I've got a list of 11 plots to be selected by their index number. If the user selects higher than 11, it should request they re-enter but atm, I get IndexError: list index out of range. I would've thought the except line would just handle anything else...but it must just be a missing line??
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"
Upvotes: 0
Views: 237
Reputation: 3149
ValueError
will come up when he user inputs something that isn't a number. (So int("hello")
throws ValueError
)
IndexError
is thrown when the user inputs a number greater than the number of elements in the list. (Eg, range(5)[7]
You may want to try getting your first input with a loop like the following
resp = ""
while resp not in ('0', '1', ... '10', 'q'):
resp = raw_input(...)
Upvotes: 0
Reputation: 298176
except ValueError
only catches a ValueError
. You need to add IndexError
as well:
except (ValueError, IndexError):
Upvotes: 4
Reputation: 1614
except ValueError
means you only catch execptions of the type ValueError
. Include a catch for IndexError
if you want to handle it differently, or catch both and handle it the same way.
Upvotes: 0