IndexError signals that an indexed access has gone beyond the available items. For example, `alist = [1, 2, 3]` followed by `alist[7]` raises `IndexError: list index out of range`. If nothing catches it, Python reports the exception at the top level. section 14.2.2
Code can raise the exception explicitly with `raise IndexError(...)`; a message argument can explain what went wrong. IndexError is a subclass of LookupError, which is a subclass of Exception. Put an `except IndexError` clause before an `except LookupError` clause if the two need different handling: the broader clause would otherwise catch both. section 14.2.2 section 14.2.7
class LineReader:
def __init__(self, filename):
self.fileobject = open(filename, 'r') #1
def __getitem__(self, index):
line = self.fileobject.readline() #2
if line == "": #3
self.fileobject.close() #4
raise IndexError #5
else:
return line.split("::")[:2] #6
for name, age in LineReader("filename"):
. . . do whatever . . .
The `LineReader` example defines `__getitem__` to return successive file lines. At end of file, it closes the file and raises IndexError, ending the enclosing `for` loop. section 17.7 section 17.7.1
That file reader is illustrative, not usually the simplest way to iterate over a file; `for line in fileobject` is generally sufficient. Likewise, do not add an IndexError handler merely because a requested count exceeds a list’s length: first check whether the code can actually raise one. section 17.7.1 section 14.4.2
