Handling a File Error
As already pointed out in the exceptions lesson, Python contains a vast set of built-in exceptions. One important class has to do with file handling. The example presented in the lesson will help to review file handling methods and put them in the context of handling exceptions.
Catching Specific Exceptions
The proper way of handling exceptions in Python is to specify what exception are we expecting. In this way, we know that if the problem is that the file doesn't exist, we can create it, while if the problem is of a different nature, it will be raised and displayed to the user. We can alter the above examples like this:
try:
file = open('my_file.dat')
data = file.readfile()
print('Data Loaded')
except FileNotFoundError:
print('This file doesn\'t exist')
If you run the script, and the file my_file.dat doesn't exist, it will print to screen that the file doesn't exist and the program will keep running. However, if the file does exist, you will see the exception with
readfile
. Of course, you are not limited to printing a message when an exception happens. In the case of the non-existing file, it is easy to create one:
try:
file = open('my_file.dat')
data = file.readfile()
print('Data Loaded')
except FileNotFoundError:
file = open('my_file.dat', 'w')
print('File created')
file.close()
If you run the script once, you will see that the file is being created. If you run the script a second time, you will see the exception with the readfile
method. Imagine that you don't specify which exception you are catching, and you have the following code, what will happen when you run it?:
try:
file = open('my_file.dat')
data = file.readfile()
print('Data Loaded')
except:
file = open('my_file.dat', 'w')
print('File created')
If you look carefully, you will realize that even if the file my_file.dat exists, an exception is going to be raised because of the
readfile
method. Then the except
block is going to be executed. In this block, the program is going to create a new
my_file.dat, even if it already existed, and therefore you are going to lose the information stored in it.