简体   繁体   English

尝试除了没有捕获 IndexError

[英]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:我正在尝试使用 try/except 捕获索引错误,但我仍然收到以下错误:

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).如果 test[2] 不存在,那么我知道 test_list[2] 是列表中的最后一个(即尾部)。

Your error are in line 22. There is no indexerror occur in your try catch block您的错误在第 22 行。您的 try catch 块中没有 indexerror 发生

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" !如果将长度大于 2 的列表传递给 function Linked,则不会有任何异常,因此不会出现“Tail Found”!

You gave a list with length 3, then you got a test with length 3-1.你给出了一个长度为 3 的列表,然后你得到了一个长度为 3-1 的测试。 Index text allowed only for 0 or 1, test[2] certainly get a result索引文本只允许 0 或 1,test[2] 肯定会得到结果

IndexError: list index out of range IndexError:列表索引超出范围

If you print(Linked(test_list)) , you will get:如果你print(Linked(test_list)) ,你会得到:

[<__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) .列表中只有 2 个元素,因此不能调用 index 2 (third element)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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