Properly use try-finally for file handle management

Ref #10658