Let's say I have a function (mnHw
) that calculates the mean of a vector (a vector of homework grades). This function throws a domain_error("Student did no homework")
exception when the vector is empty. When I call mnHw
from main
, things are simple when I want to print out the error:
try
{
cout << mnHw(student.homework);
}
catch (domain_error e)
{
cout << e.what();
}
However, things are complicated if I only want to store the mean homework grade, instead of vector of all grades, for the student. In that case I call mnHw
within the function that reads in the student information (readStudent
), and put up a flag (-1) when no homework is entered:
try
{
student.finalGrade=mnHw(hwGrades);
}
catch (domain_error e)
{
student.finalGrade = -1;
}
Then, within main
, I can do the following to recover the error:
if (allStudents[i].finalGrade == -1)
cout << "Student did no homework";
else
cout << allStudents[i].finalGrade;
Intuitively, though, this flag method seems less elegant than having the actual error message pass directly to main, at least for those cases when I want to display it from main (which is the case here). Is there some trick or technique I am missing that would directly give main
access to e.what()
from mnHw
?
What is good practice?
Note I have full functions for each of these cases that I could post, but they seemed too long. Please let me know if I should have included them to make myself more clear. Also, please feel free to correct any other mistakes I’m making. I am just now learning C++ the right way, and want to be corrected as much as possible. <flame-retardant vest>