Add error handling and clean up code