Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Compared to some other core language topics we’ve met in this book, exceptions are a fairly lightweight tool in Python. Because they are so simple, let’s jump right into some code.
Suppose we write the following function:
>>>def fetcher(obj, index):...return obj[index]...
There’s not much to this function—it simply indexes an object on a passed-in index. In normal operation, it returns the result of a legal index:
>>>x = 'spam'>>>fetcher(x, 3)# Like x[3] 'm'
However, if we ask this function to index off the end of the
string, an exception will be triggered when the function tries to
run obj[index]. Python detects
out-of-bounds indexing for sequences and reports it by
raising (triggering) the built-in IndexError exception: