# 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?
You shouldn’t be writing to the file in the
finallyblock as any exceptions raised there will not be caught by theexceptblock.The
exceptblock executes if there is an exception raised by the try block. Thefinallyblock always executes whatever happens.Also, there shouldn’t be any need for initializing the
filevariable tonone.The use of
returnin theexceptblock will not skip thefinallyblock. 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:
A much cleaner way of doing this is using the
withstatement: