I don't understand "finally" in try blocks


#1

I don’t get the point of “finally”. (i’m reading 7.4) If it executes no matter what why not unindent f.close() and put it under the try block. i’m missing something.

try:
    f = open("my_file.txt", "w")
    try:
        f.write("Writing some data to the file")
    finally:
        f.close()
except IOError:
    print("Error: my_file.txt does not exist or it can't be opened for output.")

#2

Good question.

In this specific example, if you remove the finally block, your code will look like this.

try:
    f = open("my_file.txt", "w")
    try:
        f.write("Writing some data to the file")
   f.close()
except IOError:
    print("Error: my_file.txt does not exist or it can't be opened for output.")

If an error occurred during file writing, you will have nothing to catch the error and the program will crash.

When the program crashes, the f.close() line will not be reached. This means you’ll still have an open file (because the code wasn’t ran to close it). This can become problematic when you try to write to the file again. Because it was never closed, you may not be able to access it.

Hope this helps.


#3

This was a great question which prompted me to do a little bit of research. I think @Romeo’s answer implied it but didn’t explicitly stated it: The code in the finally block is executed no matter what, even if there is an unhandled exception in any of the try block sections.

Check Python Tutorial - 8.6. Defining Clean-up Actions. It’s explained pretty well there.