Fix potential buffer leak if an IO exception occurs on close