54
# Open new file to write
file = None
try:
    file = open(filePath, 'w')
except IOError:
    msg = ("Unable to create file on disk.")
    file.close()
    return
finally:
    file.write("Hello World!")
    file.close()

The above code is ripped from a function. One of the user's system is reporting an error in line:

file.write("Hello World!")

error:

AttributeError: 'NoneType' object has no attribute 'write'

Question is, If python is failed to open given file, 'except' block executes and it has to return, but control is getting transferred to the line that is throwing given error. The value of 'file' variable is 'None'.

Any pointers?

0

8 Answers 8

116

You shouldn't be writing to the file in the finally block as any exceptions raised there will not be caught by the except block.

The except block executes if there is an exception raised by the try block. The finally block always executes whatever happens.

Also, there shouldn't be any need for initializing the file variable to none.

The use of return in the except block will not skip the finally block. By its very nature it cannot be skipped, that's why you want to put your "clean-up" code in there (i.e. closing files).

So, if you want to use try:except:finally, you should be doing something like this:

try:
    f = open("file", "w")
    try:
        f.write('Hello World!')
    finally:
        f.close()
except IOError:
    print 'oops!'

A much cleaner way of doing this is using the with statement:

try:
    with open("output", "w") as outfile:
        outfile.write('Hello World')
except IOError:
    print 'oops!'
5
  • 2
    Unfortunately, with is not present in python 2.4, so it won't work. Dec 11, 2013 at 8:53
  • Where is the place that "clean-up" code executed in the with version?
    – fwonce
    Jan 25, 2017 at 4:21
  • 1
    @Acorn - quick question, the outfile.close() statement is missing off the with version of the code. Is this because by using with the file will only be open within the block and now does not need to be closed? On a related note, try-except-finally catches mistakes and then any lines outside the block that follow the block should not execute. So, a third alternative might be to simply put the outfile.close() statement at the end of the code outside try-except and not use finally ? I am learning from this code. Just curious.
    – TMWP
    Apr 5, 2017 at 22:06
  • 1
    @TMWP python.org/dev/peps/pep-0343/#id46 I'm new to Python, too. I guess this is what you are looking for. "A template for opening a file that ensures the file is closed when the block is left"
    – LiweiZ
    Sep 1, 2017 at 5:36
  • 2
    The with command automatically closes the file for you. Available from Python 2.5 Dec 24, 2019 at 19:55
36

If the file is not opened, the line file = open(filePath, 'w') fails, so nothing gets assigned to file.

Then, the except clause runs, but nothing is in file, so file.close() fails.

The finally clause always runs, even if there was an exception. And since file is still None you get another exception.

You want an else clause instead of finally for things that only happen if there was no exception.

    try:
        file = open(filePath, 'w')
    except IOError:
        msg = "Unable to create file on disk."
        return
    else:
        file.write("Hello World!")
        file.close()

Why the else? The Python docs say:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

In other words, this won't catch an IOError from the write or close calls. Which is good, because then reason woudn't have been “Unable to create file on disk.” – it would have been a different error, one that your code wasn't prepared for. It's a good idea not to try to handle such errors.

4
  • But what if the file.write() raises an exception - which is entirely possible after opening, even though it was opened with write permissions. Best to include that in the try: block
    – jenming
    Dec 6, 2012 at 22:23
  • 1
    @jenming: Well, pretty much anything can raise exceptions :) You should really try to only handle exceptions you expect, though. If you're worried about exceptions from file.write(), then include it in the try; just be sure to not include something like file.write("result: %s" % do_calculation()), as that would hide exceptions from do_calculation. Dec 10, 2012 at 9:34
  • Can file.write("Hello World!") be inside of try in case to detect if something goes wrong? @PetrViktorin
    – alper
    Apr 14, 2020 at 1:19
  • @alper: Yes, it can—but you should only put it there if you can anticipate what could go wrong and how to react properly. Otherwise, let the exception be raised. Jul 13, 2020 at 14:24
7

what is the logic in including the

file.write("Hello World!")

inside the finally clause?? i think it must be put in try clause itself.

try:
        file = open(filePath, 'w')
        file.write("Hello World!")
except IOError:
        print("Unable to create file on disk.")
finally:
        file.close()
2

You can do something like this:

try:
    do_some_stuff()
finally:
    cleanup_stuff()
2

Here is the most direct solution to your problem. I use the idiom of checking for file_obj != None in the finally block.

By the way, you should be aware that file is a Python class name, so you should choose a different variable name.

file_obj = None
try:
    file_obj = open(filePath, 'w')
except IOError:
    msg = ("Unable to create file on disk.")
    file_obj.close()
    return
finally:
    if file_obj != None:
        file_obj.write("Hello World!")
        file_obj.close()
1

except does not execute (because type is IOError) it's the finally part that throws another error of type AttributeError because file = None.

0

finally always gets called in the "end", even if an exception ocurrs. You can use this to make sure open resources are closed (for instance, a DB connection, a file, etc).

I think you misunderstood the semantics.

Your logic should be in the "try", you should deal with exceptions in the "except" block, and "finally" executes no matter how your method terminates, use it to clean up.

0
-2

It is always advisable to write your logic or code that might throw an exception in the try block and use the finally block for closing the resources.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.