properly handle file closing in error cases (closes #22266)