 <p>If the file is not opened, the line <code>file = open(filePath, 'w')</code> fails, so nothing gets assigned to <code>file</code>.</p> <p>Then, the <code>except</code> clause runs, but nothing is in file, so <code>file.close()</code> fails.</p> <p>The <code>finally</code> clause always runs, even if there was an exception. And since <code>file</code> is still None you get another exception.</p> <p>You want an <code>else</code> clause instead of <code>finally</code> for things that only happen if there was no exception.</p> <pre><code> try: file = open(filePath, 'w') except IOError: msg = "Unable to create file on disk." return else: file.write("Hello World!") file.close() </code></pre> <hr> <p>Why the <code>else</code>? The <a href="http://docs.python.org/tutorial/errors.html">Python docs</a> say: </p> <blockquote> <p>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.</p> </blockquote> <p>In other words, this won't catch an <code>IOError</code> from the <code>write</code> or <code>close</code> 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.</p>