Fixed issue of not closing the file handle if there was an error