Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index that caused an IndexError exception

Is it possible to get the index that caused an IndexError exception?

Sample code :

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?
like image 699
PKaura Avatar asked May 24 '14 06:05

PKaura


2 Answers

There's no direct way, because unlike KeyError, IndexError doesn't provide this information (yet). You can subclass the built-in list to raise IndexError with arguments you want:

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')

Actually, you don't even need to convert it back to normal list.

like image 200
vaultah Avatar answered Sep 19 '22 17:09

vaultah


Only manually; for example:

arr = [1,2,3]
try:
    try_index = 42
    print(arr[try_index])
except IndexError:
    print 'Index', try_index, 'caused an IndexError'
like image 31
timgeb Avatar answered Sep 19 '22 17:09

timgeb