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?
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
.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With