added error handling code
reformated code