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>All the answers mentioned here will suffice your requirement. But I believe the ideal way to achieve this is via using <code>decorator</code>. In fact they exist in python for such kind of scenarios. For example, create a decorator as:</p>

<pre><code>def wrap_index_error(func):
    def wrapped_func(*args, **kwargs):
        try:
            func_response = func(*args, **kwargs)
        except IndexError:
            func_response = None
        return func_response
    return wrapped_func
</code></pre>

<p>Now you can use this decorator as <code>@wrap_index_error</code> in any function where you want to catch the <code>IndexError</code> exception. For example in your case:</p>

<pre><code>@wrap_index_error
def get_item_from_list(my_list, index):
    return my_list[index]
</code></pre>

<p>Now you can make the simple call to access the value as:</p>

<pre><code>&gt;&gt;&gt; new_list = [1, 3, 5]
&gt;&gt;&gt; print get_item_from_list(new_list, 2)
5
&gt;&gt;&gt; print get_item_from_list(new_list, 8)
None
</code></pre>

<p><em>Note:</em> I am passing list as the argument to function because it is not a good practice to update the global value within function. Instead passed it as a argument. That way your code will be more modular. For example, may be you want to perform the same operation on another list?</p>

<p>To know more about Decorators, check: <a href="http://thecodeship.com/patterns/guide-to-python-function-decorators/" rel="nofollow">A guide to Python's function decorators</a></p>

python