When you throw an exception, the function stops there, and execution moves to where the exception was detected. Your function does not return anything, because the function does not return at all.
You can just do
if (avec.empty()) throw domain_error("Cannot operate on empty vector!");
And your function will exit it.
Note that you donโt have to worry about the return value (โHow can a function not return anything?โ, Etc.) because you cannot access the return value of a function that threw (and did not break) the exception even if you try.
So for example, if you do
try { std::vector<myStruct> vec; std::vector<myStruct> retval = extract_notworking(vec); print_vector(retval);
You can only access retval if the function returns correctly (i.e. does not throw away). In the example, your function will throw because vec empty, so print_vector will never be called.
Even if you do this:
std::vector<myStruct> retval; try { std::vector<myStruct> vec; retval = extract_notworking(vec); print_vector(retval); } catch (const domain_error& e) {
Since the function did not return, assigning its return value to retval did not happen, and retval is still an absolutely normal default built vector , which you can use freely. So in this example, retval not assigned, and retval not printed, because extract_networking throws an exception and execution into a catch before these two things can happen.
Seth carnegie
source share