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'
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:
* True backtracking is an advanced topic that is not part of the Python language, so I won't say much more about it here (even the generator functions and expressions we met in Chapter 20 are not true backtracking— they simply respond to next(G) requests). Roughly, backtracking undoes all computations before it jumps; Python exceptions do not (i.e., variables assigned between the time a try statement is entered and the time an exception is raised are not reset to their prior values). See a book on artificial intelligence or the Prolog or Icon programming languages if you're curious.
>>> fetcher(x, 4) # Default handler - shell interface
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in fetcher IndexError: string index out of range
Because our code does not explicitly catch this exception, it filters back up to the top level of the program and invokes the default exception handler, which simply prints the standard error message. By this point in the book, you've probably seen your share of standard error messages. They include the exception that was raised, along with a stack trace—a list of all the lines and functions that were active when the exception occurred.
The error message text here was printed by Python 3.0; it can vary slightly per release, and even per interactive shell. When coding interactively in the basic shell interface, the filename is just "<stdin>," meaning the standard input stream. When working in the IDLE GUI's interactive shell, the filename is "<pyshell>", and source lines are displayed, too. Either way, file line numbers are not very meaningful when there is no file (we'll see more interesting error messages later in this part of the book):
>>> fetcher(x, 4) # Default handler - IDLE GUI interface
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
fetcher(x, 4) File "<pyshell#3>", line 2, in fetcher return obj[index] IndexError: string index out of range
In a more realistic program launched outside the interactive prompt, after printing an error message the default handler at the top also terminates the program immediately. That course of action makes sense for simple scripts; errors often should be fatal, and the best you can do when they occur is inspect the standard error message.
Was this article helpful?