繁体   English   中英

尝试除了没有捕获 IndexError

[英]Try Except not catching IndexError

我正在尝试创建一个用于练习的链接列表。

到目前为止,这是我的代码:

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

我正在尝试使用 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

为什么不打印“发现尾巴”?

编辑:

我将代码更改为:

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)

它现在有效。

如果 test[2] 不存在,那么我知道 test_list[2] 是列表中的最后一个(即尾部)。

您的错误在第 22 行。您的 try catch 块中没有 indexerror 发生

为什么“发现尾巴”? 如果将长度大于 2 的列表传递给 function Linked,则不会有任何异常,因此不会出现“Tail Found”!

你给出了一个长度为 3 的列表,然后你得到了一个长度为 3-1 的测试。 索引文本只允许 0 或 1,test[2] 肯定会得到结果

IndexError:列表索引超出范围

如果你print(Linked(test_list)) ,你会得到:

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

看? 列表中只有 2 个元素,因此不能调用 index 2 (third element)

暂无
暂无

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

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