Handling a File Error

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:

try:
    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'
try:
    [...]
 [...]

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

filename = ''
try:
    [...]

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.