Refactor code and cleanup
handled errors with exception