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 =
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

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now