Python Exception Class Hierarchy

Python Exception Handling – KeyError

Today, as we make our way through our detailed Python Exception Handling series, we’ll be looking into the KeyError, which is the close sibling of the IndexError we looked at last week. Whereas the IndexError is raised when trying to access an invalid index within a list, the KeyError is raised when accessing an invalid key within a dict.

Throughout this article we’ll explore the KeyError in great depth by first looking at where it sits in the overall Python Exception Class Hierarchy. We’ll also show some fully functional Python code samples that illustrate the basic usage of dictionaries in Python, and how improper key access can lead to KeyErrors. Let’s go!

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 deals with lists and the KeyError deals with dicts, we should briefly explore the difference between these two common data structures in Python. Python’s lists are similar to arrays in most other programming languages. It is an ordered collection of objects that are each assigned in incremental numeric index to identify each element. Lists are commonly used as stacks, which allows for the “first-in, last-out” behavior that is so crucial in many applications.

Dicts, on the other hand, are known as associative arrays in most other languages. A dict is also a collection of objects, but it is unordered, and instead of using numeric indices, a dict uses immutable data types as keys. When you see reference to key: value pairs in Python, this is an indication the collection holding those pairs is a dict.

To illustrate how to use dicts we’ll create a series dict object and add a trio of Books to it. Our key values are merely the relative order each book is found in the series, but we could have used anything for these keys:

Once our series dictionary has some elements we’ll output them to the console to confirm what’s in there using the log_dict(collection, include_key=False) method:

Executing our main(...) method produces the following output:

Everything looks as expected — our Books were added and are being output via the modified Book.__str__(self) method:

However, let’s see what happens if we try to access an invalid key in our dict:

Here we’re trying to access the len(series) + 1 key of the dictionary, which is a shorthand way of accessing the key of value 4. Since the series only contains three Books in total, executing this code raises a KeyError:

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!