Cleaning up code with error handling