Added error handling in write-to-file