Python列表插入操作使用try except捕获无效索引异常问题求助
问题根因
- 你的代码存在缩进错误:
try语句前有多余缩进,和第一行的collection变量定义缩进不对齐,运行会直接报语法错误。 - Python内置的
list.insert()方法本身不会抛出IndexError异常:当插入位置≥列表长度时,元素会被自动追加到列表末尾;当插入位置<0时,元素会被自动插入到列表开头,不存在越界报错的情况,因此你捕获的IndexError永远不会被触发。 - 你添加的
if location <5判断逻辑存在漏洞:长度为5的列表合法插入位置范围是0~5(插入位置为5时对应追加到列表末尾),你的判断直接过滤了合法的末尾插入位置,且不符合规则的位置仅会跳过插入逻辑,不会抛出异常。 - 现有try代码块中没有任何会触发
IndexError的执行逻辑,因此except分支永远不会运行。
修复方案
推荐优先用主动范围校验实现需求,同时补充输入非整数的异常捕获,修复后代码如下:
collection = ["plate", "fork", "knife", "spoon", "cup"] try: location = input("Where do you want to insert the new item?: ") location = int(location) newitem = input("Which item do you want to add to the list?: ") # 合法插入位置范围是 0 到 len(collection) 闭区间 if 0 <= location <= len(collection): collection.insert(location, newitem) else: # 主动触发异常匹配原有捕获逻辑 raise IndexError except ValueError: print("Please enter a valid integer for the location.") except IndexError: print("Wrong index used in accessing list. Please add a valid index") print(collection)
如果一定要通过触发原生异常实现捕获,可以主动访问对应索引位置触发IndexError,该写法冗余不推荐,仅做参考:
collection = ["plate", "fork", "knife", "spoon", "cup"] try: location = input("Where do you want to insert the new item?: ") location = int(location) newitem = input("Which item do you want to add to the list?: ") # 主动访问索引触发越界异常 if location <= len(collection): # 插入位置等于列表长度是合法场景,访问最后一位索引避免误报错 _ = collection[location if location < len(collection) else -1] collection.insert(location, newitem) else: _ = collection[location] except ValueError: print("Please enter a valid integer for the location.") except IndexError: print("Wrong index used in accessing list. Please add a valid index") print(collection)
内容的提问来源于stack exchange,提问作者Sofia A
相关产品推荐
相关产品推荐

