Python – How to you catch all index out of range errors in python

exceptionspython

Our program does these kinds of operations hundreds of times for many different variables and lists, then uses them throughout the program:

variable = values[5]

The list values are coming from the command line, often as words, paragraphs, rows of a table or other (it's not important). Our issue is that our program, which is designed to run in a continuous loop, stops when there is an index out of range error. Since this comes from the command line, we can expect these fairly often, but cannot accept our program stopping.

Thus, the question is: How can I catch all index out of range errors in python so that my program does not stop. Do I have to use try/except statements everywhere I make the above type statements (which is a lot of extra work for 40k lines of code) or can I do a catch all somehow? How the error is handled is important (I expect 99% of the time we can set it to NULL, ERROR or 0), but keeping the loop running is even more important.

Best Answer

There is no global solution that just sets the problem variable to NULL and continuous on with normal program flow. This appears to be the only way:

try:
   variable=values[5]
except:
   variable='error'

You'll have to change the original one liner to a 4 liner everywhere you use a list variable. It is the most appropriate way since it allows specific response for different variables, but it is a shame that your 10,000 line program is probably going to end up being 30,000 lines just to deal with an index out of range error. Furthermore, you cannot really use referenced lists in equations do to the lack of global error handling in python, which will bulk it up even more. For example:

string_var = "first name: " + values[5] + "last name: " + values[6]

Will not work for your program since you are not 110% certain what your lists will contain (only 99% certain). You'll have to rewrite this using multiple discrete exception handling for each list item, or one exception that has if statements for each discrete list item.

Related Topic