Ensuring file handles are closed correctly