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.
There is only one more block to discuss in the exception handling pattern, the
else block. The core idea of this block is that it gets executed if there are no
exceptions within the
try block. Is very easy to understand how it works. You could, for example, do the following:
filename = 'my_data.dat' try: file = open(filename) except FileNotFoundError: print('File not found, creating one') file = open(filename, 'w') else: data = file.read() important_data = data
The most difficult part of the else block is understanding its usefulness. In principle, the code that we have included in the
block could have also been placed right after opening the file, as we have done earlier. However, we can use the
block to prevent catching exceptions that do not belong to the
try. It is a bit of a far-fetched example, but imagine that you need to read a filename from a file and open it. The code would look like this:
try: file = open(filename) new_filename = file.readline() except FileNotFoundError: print('File not found, creating one') file = open(filename, 'w') else: new_file = open(new_filename) data = new_file.read()
Since we are opening two files, it may very well be that the problem is that the second file doesn't exist. If we would put this code into the
block, we would end up triggering the
the second file even if we didn't mean to. At first, it is not obvious the true use of the
else block, but it can be very useful and therefore it is important that you are aware that it exists.
Of course, it is possible to combine everything that you have learned so far:
try: file = open(filename) new_filename = file.readline() except FileNotFoundError: print('File not found, creating one') file = open(filename, 'w') else: new_file = open(new_filename) data = new_file.read() finally: file.close()
You are very encouraged to play around and try to find different usages for each block. If you have worked enough with Python, you probably encounter plenty of exceptions that force you to re-run your script from the beginning. Now you know that there may be workarounds. A great resource, as almost always, is the Python Documentation on Exceptions.
We're not done yet. There are many more things that can be done with exceptions.