As a Python programmer you’ve likely come across an exception—whether you realized it or not. If you try to run a script that contains a syntax error, Python raises an exception. To become a successful programmer, you’ll have to learn how to handle these errors as they arise.

In this article, we’ll learn about Python’s try and except keywords and how they’re used to handle exceptions. We’ll show an example of exception handling clauses, learn more about the context manager for exceptions, and show how to handle exceptions in an API request. 

What Is an Exception?

In the Python programming language, an exception (short for exceptional event) is an error detected during execution. Python raises an exception any time you try to divide by zero, access an unresponsive database, or indent your code improperly, among other situations.

Exceptions are also objects derived from the Python core class Exception. The Exception object contains information about the nature of the error in your code. Python provides a number of built-in exceptions, and libraries are free to extend the Exception class to implement their own.

Exceptions in Python

We use the  try and except keywords to catch, or handle, exceptions. Catching exceptions is crucial, as uncaught exceptions will cause your program to crash.

With that in mind, let’s take a look at some common exceptions in Python.

Common Python Exceptions

Python comes with quite a few built-in exceptions that it raises for common error conditions. Here are the exceptions that you’ll most often see when you start working with Python:

Exception NameDescription
AssertErrorAn exception that is raised when an assertion fails. Commonly used for debugging and unit testing. 
KeyErrorAn exception that is raised when Python cannot find a given key in a dictionary object. 
MemoryErrorThe Python exception that is raised when your program runs out of available memory.
ModuleNotFoundErrorAn exception that Python raises when the specified module cannot be found in an import statement.
NameErrorAn exception that Python raises when an undefined variable is used.
OSErrorA group of similar exceptions that are raised when your computer’s operating system has an error.
RuntimeErrorA miscellaneous exception that is raised when none of the other built-in Python exceptions apply.
StopIterationAn exception raised when you call next() on an iterator, but there are no more objects in the list to iterate through.
SyntaxErrorA Python exception that is raised when there is a problem with the syntax of your code.
TabErrorAn exception that is raised when your code has incorrect indentation.
TypeErrorThe Python exception that is raised when an object is of the incorrect data type for a given operation. 
ZeroDivisionErrorThe exception that is raised when you try to divide a number by zero.

For more Python exceptions, take a look at Python’s exception documentation. Note that each library implements its own exceptions, so you’ll likely come across exceptions other than those found in the Python manual.

Next, let’s generate an uncaught exception and see how Python deals with it.

Uncaught Exception Example

Before we begin handling errors with try and except, let’s look at what happens when your code causes an uncaught exception. As an example, let’s consider what would happen if you were to divide an integer by zero. We’ll run this code:

answer = 50 / 0
print(answer)

In mathematics, any number divided by zero results in an undefined result. In Python, this is what we get:

Recall that upon reaching an exception, Python stops executing the program on the line where it occurred. Execution never reaches the print statement, and our program crashes instead.

Now let’s look at how we can catch the exception and handle it.

Handling Exceptions With Python’s Try and Except Keywords

We know that uncaught errors cause our program to crash, so the next step is learning how to catch and handle exceptions. We’ll be using the Python keywords try and except to create blocks of code that can catch exceptions.

A try block, or clause, contains the functions and code that could raise an exception. An except clause contains the logic for handling the exception. Let’s build on our earlier code snippet and add try and except.

In this example, we’ll first define the answer variable, and then attempt to use it to store the result of a divide by zero operation. At the end, we’ll print the answer and see if it’s None or if it contains a result. Let’s take a look at the code:

answer = None
 
try:
  answer = 50 / 0
except ZeroDivisionError:
  print("[!] Exception caught")
 
print(answer)

This time we wrapped our ill-fated division operation in a try clause. Our except clause contains a print statement to let us know that it caught an exception. Finally, we print the answer. Here’s the output we get from running our code:

As you can see, the exception was caught in the try block, the answer variable remained untouched, and the program didn’t crash. To drive the point home, let’s try the same code again, this time dividing by two instead of zero:

answer = None
 
try:
  answer = 50 / 2
except:
  print("[!] Exception caught")
 
print(answer)

We’ll run the code and look at the output:

This time the code in our except block never ran, so we know there was no exception. We receive the expected result. 

Using the Exception Context Manager

We can improve upon our previous code by trapping the exception we caught in the except clause and learning more about it. We do this by using an exception context manager and storing the exception object in a variable. Then we’re free to work with the exception like any other object. Here’s a snippet:

except Exception as err:
     print(f"[!] Exception caught: {err}")

The code above catches every error of the type Exception and passes it to the except clause in a variable named err. This lets us print err to learn more about the exception. 

Next, let’s take a look at Python’s try and except keywords in a real-world example using a context manager.

Exception Handling in Python: An Example

If you’ve ever seen a 404 message while browsing the web, you know that errors can occur while making HTTP requests. In Python, we have to deal with HTTP errors while making requests to an API server. Sometimes the server is unavailable, or your network connection is disrupted, and Python raises an exception.

Handling Exceptions in HTTP Requests 

In this example, we’ll use Python’s try and except keywords to write a function that makes an API request. Our code will attempt to make a request from the server, and if it fails we’ll catch the exception and try again.

Let’s start by importing the libraries we need and defining some variables. We’ll need the requests library to make the HTTP request to our API server, and the time library to introduce a short delay between API requests. We’ll store the URL of the API server in our url variable, and define an empty response variable for the request.

import requests
import time
 
url = "https://reqres.in/api/users"
response = None

With that in place, let’s create the loop that we’ll use to continually make requests until we receive a response. Following our while loop, we’ll wrap the request in a try statement and store the response.

while response is None:
  try:
     response = requests.get(url)

If the request fails to reach the server for any reason, we’ll need to handle the exception. We’ll use the except statement and create an exception context manager. If our request causes an error, we’ll catch it here, print the exception, and wait five seconds before trying again:

except requests.HTTPError as e:
     print(f"[!] Exception caught: {e}")
     time.sleep(5)

Once our request succeeds, we’ll print the response:

print(response.content)

Here’s the exception handling code in full:

import requests
import time
 
url = "https://reqres.in/api/users"
response = None
 
while response is None:
  try:
     response = requests.get(url)
  except requests.HTTPError as e:
     print(f"[!] Exception caught: {e}")
     time.sleep(5)
 
print(response.content)

Now let’s demonstrate a few exceptions and show how the code retries the request until it succeeds. To facilitate this, we disabled our internet connection and ran the code. 

As expected, we see a number of exceptions printed on the screen. After reconnecting to the internet, we see the response generated by a successful request:

The screenshot above may be unclear on your screen, so let’s zoom in and look at a single exception in more detail:

Python’s requests library raised an HTTPSConnectionPool error. It was caused by a NewConnectionError in the underlying urllib library, and the reason for the error was a temporary failure in name resolution. That’s exactly what we’d expect if our computer were disconnected from the internet. 

Learn To Code With Udacity

Now that you’ve learned the basics of exception handling in Python, consider going back to your older projects and adding it. You’ll find that robust error handling will make your software more stable and reliable for your users. 

To learn the core concepts of programming through HTML, CSS, and Python, check out Udacity’s Introduction to Programming nanodegree. It’s your first step toward a career as a computer programmer.