Introduction
We’ve seen a lot of exceptions so far:
SyntaxError
IndentationError
AttributeError
NameError
TypeError
IndexError
ValueError
ZeroDivisionError
FileNotFoundError
These are exceptions defined by Python, and which are raised when certain errors occur. (There are many, many other exceptions that are outside the scope of this textbook.)
When an unhandled exception occurs, your program terminates. This is usually an undesired outcome.
Here we will see that some of these exceptions can be handled gracefully using try
and except
—these go together, hand in hand. In a try
block, we include the code that we think might raise an exception. In the following except
block, we catch or handle certain exceptions. What we do in the except
block will depend on the desired behavior for your program.
However, we’ll also see that some of these—SyntaxError
and IndentationError
for example—can’t be handled, since these occur when Python is first reading your code, prior to execution.
We’ll also see that some of these exceptions only occur when there’s a defect in our code that we do not want to handle! These are exceptions like AttributeError
and NameError
. Trying to handle these covers up defects in our code that we should repair. Accordingly, there aren’t many cases where we’d even want to handle these exceptions.
Sometimes we want to handle TypeError
or IndexError
. It’s very often the case that we want to handle ValueError
or ZeroDivisionError
. It’s almost always the case that we want to handle FileNotFoundError
. Much of this depends on context, and there’s a little art in determining which exceptions are handled, and how they should be handled.
Learning objectives
- You will understand why many of the Python exceptions are raised.
- You will learn how to deal with exceptions when they are raised, and how to handle them gracefully.
- You will learn that sometimes it’s not always best to handle every exception that could be raised.
Terms introduced
- exception handling
- “it’s easier to ask forgiveness than it is to ask for permission” (EAFP)
- “look before you leap” (LBYL)
- raise (an exception)
- try/except
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.