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.
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.
try: print("Hello Learners!" + 777) except: 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.
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
try: 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: print(type(error)) print(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.
try: with open("highscore.txt", "r") as f: highscore = f.read() highscore = int(highscore) print("The highest score previously was ") print(highscore) except FileNotFoundError: print("Creating a new highscore.txt file") f = open("highscore.txt", "w") f.write("0") f.close() highscore = 0
Test the code
Run the code and note how the
highscore.txt file is created if it didn’t previously exist.
Can you think of any other errors or exceptions that may occur? Share your ideas in the comments section.