Make sure file handles are closed properly, even when an exception is thrown