简体   繁体   中英

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 (ie the tail).

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

Why "Tail Found"? If you pass a list with length greater than 2 to function Linked, there won't be any exception, so no "Tail Found" !

You gave a list with length 3, then you got a test with length 3-1. Index text allowed only for 0 or 1, test[2] certainly get a result

IndexError: list index out of range

If you print(Linked(test_list)) , you will get:

[<__main__.Node object at 0x02A62220>, <__main__.Node object at 0x02AC1220>]

See? Only 2 elements in the list, so you can't call index 2 (third element) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM