Catch the error and close the file handle first