£199.99 £139.99 for one year of Unlimited learning. Offer ends on 14 November 2022 at 23:59 (UTC). T&Cs apply

Find out more
Exception handling
Skip main navigation

Exception handling

Exception handling is vital for dealing with errors that are expected in a program.

When you tried to open a file that didn’t exist, Python raised an error. In this step you will explore how to deal with errors as they occur.

The try...except statement

Programming languages have ways to handle exceptions (issues or problems that occur when code is run). In Python there is a try...except statement that is used for such an occasion. This is often also known as a try, catch.

The statement works by first trying to run code that is indented inside the try statement. If there is an error or exception, the error is caught, the except is triggered, and the code indented under except is executed.

print("Hello Learners!" + 777)
print("Oh dear! A string and integer cannot be concatenated")

In this example the try statement will attempt to print a message. If any error occurs, then the except part will be triggered and print the error message.

Mu showing the above program with the messsage "Oh dear! A string and integer cannot be concatenated" in the REPL

It is not good practice to catch all errors, because if an error occurs that you weren’t expecting, it should not be hidden from the user. Your program should anticipate the type of error that you wish to catch and then take an appropriate action.

The type of error raised by the above program is a TypeError. You can explicitly tell the except to only catch TypeError using except TypeError.

print("Hello Learners!" + 777)
except TypeError:
print("Oh dear! A string and integer cannot be concatenated")

You can also retrieve information about the error using except TypeError as error, which will allow you to print the error type and message.

except TypeError as error:

Adding exception handling to the game

In the game you used the highscore.txt file to store the highest score. When there was no highscore.txt file, the code raised an error. Delete your highscore.txt file and reload the game to see the error message again. Using exception handling, the program can be adapted to handle errors in a friendlier manner.

This code snippet adds an exception handler to your game. It tries to open the highscore.txt file and read the contents; if the highscore.txt file does not exist, a FileNotFoundError error will be raised. The program will then create the file and write 0 to it.

with open("highscore.txt", "r") as f:
highscore = f.read()
highscore = int(highscore)
print("The highest score previously was ")
except FileNotFoundError:
print("Creating a new highscore.txt file")
f = open("highscore.txt", "w")
highscore = 0

Test the code

Run the code and note how the highscore.txt file is created if it didn’t previously exist.

mu running the program above showing the message "Creating a new highscore.txt file"

Can you think of any other errors or exceptions that may occur? Share your ideas in the comments section.

This article is from the free online

Programming 103: Saving and Structuring Data

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education