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.

Exceptions in Exceptions

Imagine that the code is part of a larger function, responsible for opening a file, loading its contents or creating a new file in case the specified filename doesn't exist. The script will look the same as earlier, with the difference that the filename is going to be a variable:

    file = open(filename)
    data = file.readfile()
except FileNotFoundError:
    file = open(filename, 'w')

To run the code above, the only thing you have to do is to specify the filename before, for instance:

filename = 'my_data.dat'

If you run this code, you will notice that it behaves exactly as expected. However, if you specify an empty filename:

filename = ''

You will see a much longer error printed to screen, with one important line:

During handling of the above exception, another exception occurred:

If you look carefully at the error, you will see that it outputs information regarding that an error occurred while the code was already handling another error. This is, unfortunately, a common situation, especially when dealing with user input. The way around it would be to nest another try/except block or to verify the integrity of the inputs before calling open.