How to catch an index error
<p>Given <code>mylist = [0, 1]</code></p>

<pre><code>def catch_index_error(value):
    try:
        return value
    except IndexError:
        return None

catch_index_error(mylist[5])
</code></pre>

<p>returns an <code>IndexError</code></p>

<p>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?</p>

<p>The expression <code>mylist[5]</code> causes the <code>IndexError</code>, because it is evaluated <em>before</em> the function is called.</p>

<p>The only way to fix this is by letting the function return the correct value <em>from <code>mylist</code></em>:</p>

<pre><code>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
</code></pre>

python