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

--HG--
branch : 2.7