Semantics of file.close()

Matimus mccredie at gmail.com
Mon Jul 16 20:13:35 EDT 2007


> How do I ensure that the close() methods in my finally clause do not
> throw an exception?

You have no choice. If close is going to fail, it will fail.
Fortunately you can catch the exception and continue on.
<code>
try:
    try:
        file1.write(somestuff)
    finally:
        file1.close()
except IOError:
    pass
</code>
or you could wrap it in the inner scope:
<code>
try:
    file1.write(somestuff)
finally:
    try:
       file1.close()
    except IOError:
        pass
</code>

This doesn't prevent the exception from happening, but it prevents the
user for seeing it. Also, you don't need to use semicolons in python.




More information about the Python-list mailing list