error handling for loop added