AutomaticStatic AutomaticStatic - 1 year ago 77
Python Question

How to catch an index error


mylist = [0, 1]

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


returns an

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 Source

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):
     return mylist[index]
  except IndexError:
    return None

catch_index_error(0) # returns '0'
catch_index_error(4) # returns None
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download