I was asked to use try-catch exception handling to handle the case if the list o
ID: 3685799 • Letter: I
Question
I was asked to use try-catch exception handling to handle the case if the list of students is empty. I'm new to c++ so can anyone guide me?
double classAverage()
{
int count = 0;
double sum = 0.0;
Container *temp = list;
if (temp == NULL)
{
cout << "List empty!";
return -1.0;
}
while (temp != NULL)
{
sum += temp->student->getGrade();
temp = temp->next;
count++;
}
return sum / count;
}
Explanation / Answer
#include <iostream>
using namespace std;
double classAverage()
{
int count = 0;
double sum = 0.0;
Container *temp = list;
if (temp == NULL)
{
throw "list of students is empty!";
}
while (temp != NULL)
{
sum += temp->student->getGrade();
temp = temp->next;
count++;
}
return sum / count;
}
int main ()
{
double average = 0;
try
{
average = classAverage();
cout << average << endl;
}
catch (const char* msg)
{
cerr << msg << endl;
}
return 0;
}
NOTE: if you given full prog i can give you output, (Container is not implemented)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.