AutomaticStatic AutomaticStatic - 2 months ago 5
Python Question

How to catch an index error

Given

mylist = [0, 1]


def catch_index_error(value):
try:
return value
except IndexError:
return None

catch_index_error(mylist[5])


returns an
IndexError


The argument is evaluated prior to the function being executed and therefore the function can't catch the exception. Is there a way of catching it?

Answer

The expression mylist[5] causes the IndexError, because it is evaluated before the function is called.

The only way to fix this is by letting the function return the correct value from mylist:

mylist = [0,1]
def catch_index_error(index):
  try:
     return mylist[index]
  except IndexError:
    return None

catch_index_error(0) # returns '0'
catch_index_error(4) # returns None