Ensure file handles are closed when exception occurs in lines 206 - 217