获取导致IndexError异常的索引

时间:2014-05-24 06:56:02

标签: python python-2.7

是否有可能获得导致IndexError异常的索引?

示例代码:

arr = [0, 2, 3, 4, 5, 6, 6]
try:  
   print arr[10] # This will cause IndexError
except IndexError as e:
    print e.args # Can I get which index (in this case 10) caused the exception?

3 个答案:

答案 0 :(得分:6)

没有直接的方法,因为与KeyError不同,IndexError尚未提供此信息。您可以使用您想要的参数将内置list子类化为IndexError

class vist(list): # Verbose list
    def __getitem__(self, item):
        try:
            v = super().__getitem__(item) # Preserve default behavior
        except IndexError as e:
            raise IndexError(item, *e.args) # Construct IndexError with arguments

        return v

arr = [0, 2, 3, 4, 5, 6, 6] # list
arr = vist(arr) # vist

try:
    arr[10]
except IndexError as e:
    print(e.args) # (10, 'list index out of range')

实际上,您甚至不需要将其转换回正常list

答案 1 :(得分:5)

仅手动;例如:

arr = [1,2,3]
try:
    try_index = 42
    print(arr[try_index])
except IndexError:
    print 'Index', try_index, 'caused an IndexError'

答案 2 :(得分:4)

除了手动跟踪您访问的索引外,我不相信,至少不是2.7。除非我误读了提案,there is a proposal for this in 3.5