Python Exception Class Hierarchy

Python Exception Handling – IndexError

Moving right along through our in-depth Python Exception Handling series, today we’ll be going over the IndexError, in all its glory. The IndexError is one of the more basic and common exceptions found in Python, as it is raised whenever attempting to access an index that is outside the bounds of a list.

In today’s article we’ll examine the IndexError in more detail, starting with where it resides in the larger Python Exception Class Hierarchy. We’ll also look into some functional Python sample code that will illustrate how basic lists are used and improper indexing can lead to IndexErrors. Let’s get into it!

The Technical Rundown

All Python exceptions inherit from the BaseException class, or extend from an inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

Since the IndexError is raised when dealing with lists, our code sample is setup to handle the basic creation and iteration of a list of Books. The log_list(collection, include_index=False) method iterates through the passed collection list by converting to an enumeration, then outputting each item (with or without the index):

To test this out we start by creating a new list and appending a handful of books (from a great fantasy series, by the way) onto it:

Now, we need to pass our books list to the log_list(...) method, so we’ll confirm that both the basic and index-included outputs work:

As expected, this code works as it should and outputs the following Book details to the console:

Just like arrays and other common collections in programming, Python lists are zero-indexed, so our three elements are only indexed up to a maximum of 2. However, let’s see what happens if we try to access index 3 of the books list:

As you probably suspect, this raises an IndexError, indicating that the list index is out of range:

Airbrake’s robust error monitoring software provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake’s state of the art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. No matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize exception parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.

Check out Airbrake’s error monitoring software today and see for yourself why so many of the world’s best engineering teams use Airbrake to revolutionize their exception handling practices!