I’m just learning C++, and would like to throw an exception, but then the result of my function would be undefined???
std::vector<myStruct> extract_notworking(std::vector<myStruct>& avec){
std::vector<myStruct> result;
if (avec.size() == 0)
//throw domain_error("Cannot operate on empty vector!");
//Cannot use exception for it would yield undefined result
return result;
//do something here
//...
return result;
}
What should I do? Return an empty vector? What would happen if I threw the exception to the receiver of the return value?
When you throw an exception, the function halts there and execution jumps to wherever the exception was caught. Your function doesn’t return anything because the function doesn’t return at all.
You can just do
And your function will exit there.
Note that you don’t need to be concerned about the return value (“How can a function not return anything?” etc) because you can’t access the return value of a function that threw (and did not catch) an exception even if you try.
So for instance, if you do
You can only access
retvalif the function returns properly (i.e. does not throw). In the example, your function will throw becausevecis empty, soprint_vectorwill never be called.Even if you do this:
Since the function did not return, the assignment of its return value to
retvaldid not happen, andretvalis still a perfectly normal default-constructedvectorthat you can use freely. So in that example,retvalis not assigned to andretvalis not printed, becauseextract_networkingthrew an exception and execution jumped into thecatchblock before those two things could happen.