Search code examples
pythonlinked-listindex-error

Try Except not catching IndexError


I'm trying to create a linked list for practice.

Here is my code so far:

class Node:
    def __init__(self, data, _next):
        self.data = data
        self._next = _next

test_list = [1,4,9]


def Linked(nodes):
    try:
        linked = []
        for i in range(len(nodes)-1):
            j = Node(nodes[i], nodes[i+1])
            linked.append(j)
        return linked
    except IndexError:
        print('Tail Found')

test = Linked(test_list)


test[2].data

I'm trying to catch the Index Error with the try/except but I'm still getting the following error:

IndexError                                Traceback (most recent call last)
<ipython-input-193-5fa4e0d033a1> in <module>
     20 
     21 
---> 22 test[2].data

IndexError: list index out of range

Why isn't it printing 'Tail Found'?

EDIT:

I changed the code to this:

class Node:
    def __init__(self, data, _next):
        self.data = data
        self._next = _next

test_list = [1,4,9]


def Linked(nodes):
        linked = []
        for i in range(len(nodes)-1):
            j = Node(nodes[i], nodes[i+1])
            linked.append(j)
        return linked


test = Linked(test_list)

try:
    print(test[2].data)
except IndexError:
    print('Tail Found: '+test[1]._next)

And it works now.

If test[2] doesn't exist then I know that test_list[2] is the last one in the list (i.e. the tail).


Solution

  • Your error are in line 22 . There is no indexerror occur in your try catch block