简体   繁体   中英

Throwing an error to main from a function called by another function

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>

You can re-throw the exception catched (const domain_error* e){ throw e;} . Or better, you can create based on domain_error create another exception ie, student_final_grade_exception and throw it.

EDIT:

Something like:

 try
        {
            student.finalGrade=mnHw(hwGrades);
        }
        catch (domain_error& e)
        {
              student_final_grade_exception mean_excep;
              mean_excep.addInfo("Error in calculation means...");
              mean_excep.addInfo(e.what()); 
              throw mean_excep;
        }

And then, you prepare your main to catch student_final_grade_exception . Of course, there is a litle bit more work to create a new exception type, but it can make possible to get more info and let the functions to only what they suppose to do as were told.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM