Good. As you could see, when we work with text files, it's possible that things can go wrong. For example, a file we're trying to open on the user's computer may not exist, or it may contain a letter when we expect a number. Such situations are called exceptions (exceptional, or unexpected, circumstances).
By default, Python will show its own kind of error message and stop the program when it encounters an exception, as you could see in the experiment. We can change that behavior using
except blocks, which allow our code to handle the exception. Take a look:
with open('misssing_file.txt', 'r') as file:
print('Could not read the file.')
In the code above, we try to execute the code in the
try block. The code opens the file and prints its contents to the console. We know this code may fail. Specifically speaking, we expect that an
IOError may occur. IO stands for Input-Output. An Input-Output error is one related to handling files – such as a full disk or nonexistent file – and other user input errors. If an IO error is thrown by the application, the execution of the
try block is interrupted, and Python moves on to the
except-block. In this case, we print our custom error message:
Could not read the file.
When we handle an exception in the
except block, the program execution is not interrupted – any further code can be still executed.
Python comes with many kinds of built-in error types, and
IOError is just one of them.