Want to keep learning?

This content is taken from the Raspberry Pi Foundation & National Centre for Computing Education's online course, Programming 103: Saving and Structuring Data. Join the course to learn more.

Exception handling

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.

Share this article:

This article is from the free online course:

Programming 103: Saving and Structuring Data

Raspberry Pi Foundation