5.1 Introduction to Exceptions#

In the last chapter, we went through a few examples to give you an idea of how to catch and handle exceptions. There’s more to know about options for handling exceptions, so let’s take a closer look. Please refer to the Python documentation on exceptions for full details. The sections on handling exceptions and defining clean-up actions are particularly relevant.

Before we launch in, let’s clear up some terminology.

In programming, an exception refers to an unusual event that disrupts the normal flow of control. Various languages have different features for defining, raising, and handling exceptions, and they may use different terminology. For example, in Java, a distinction is made between “exceptions” and “errors”. In Python, there is no separate category for “errors”. Every kind of exception, whether a built-in type of exception or one that we define ourselves, is a subclass of Exception.[1]

Raising an exception refers to what happens when a program creates an instance of an exception class and interrupts normal execution of the program’s code. We can raise an exception directly by using the keyword raise, or we can cause it to happen indirectly by writing code in a way that raises an error, as in this line:

int('good luck converting this to an int!')

We also talk about throwing an exception, which means the same thing as raising an exception. This terminology alludes to a metaphor: you can think of an exception as a hot potato that no one wants to hold, so they keep throwing it to someone else. Perhaps eventually someone is willing to handle the hot potato and therefore doesn’t pass it on.

Catching an exception means handling it and allowing normal program execution to resume.