Handle IO exception when writing to file