Chapter 5. Exceptions and Errors

Errors happen. That’s why every practical programming language provides a rich framework for dealing with them.

Python’s error model is based on exceptions. Some of you reading this are familiar with exceptions, and some are not. Some of you have used exceptions in other languages, but not yet with Python. This chapter is for all of you.

If you are familiar with how exceptions work in Java, C++, or C#, you’ll find Python uses similar concepts, even if the syntax is rather different. And beyond those similarities lie uniquely Pythonic patterns.

We start with the basics. Even if you’ve used Python exceptions before, I recommend reading all of this chapter. Odds are you will learn useful things, even in sections which appear to discuss what you’ve seen before.

The Basic Idea

An exception is a way to interrupt the normal flow of code. When an exception occurs, the block of Python code will stop executing—literally in the middle of the line—and immediately jump to another block of code, designed to handle the situation.

Often an exception means an error of some sort, but it doesn’t have to be. It can be used to signal anticipated events, which are best handled in an interrupt-driven way. Let’s illustrate the common, simple cases first, before exploring more sophisticated patterns.

You’ve already encountered exceptions, even if you didn’t realize it. Here’s a little program using a dict:

# favdessert.py
def describe_favorite(category):
    "Describe my ...

Get Powerful Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.