error handling added to write a file function