Add properly IO handling on close.

On the M-Lab platform, we are seeing fairly chronic errors. I cleaned up the IO handling, especially to move close attempts to a finally block to ensure they are always attempted and hence underlying OS resources less likely to be left in inconsistent states.