Throw exception and return result from a function

Mihaela picture Mihaela · Mar 3, 2012 · Viewed 17.1k times · Source

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?

Answer

Seth Carnegie picture Seth Carnegie · Mar 3, 2012

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

if (avec.empty())
    throw domain_error("Cannot operate on empty vector!");

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

try {
    std::vector<myStruct> vec;

    std::vector<myStruct> retval = extract_notworking(vec);

    print_vector(retval); // this line is only executed if extract_networking
                          // does not throw an exception
} catch (const domain_error& e) {
    // we can't access retval here so no worries
}

You can only access retval if the function returns properly (i.e. does not throw). In the example, your function will throw because vec is 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) {
    // we can access retval here but the assignment never happened
}

Since the function did not return, the assignment of its return value to retval did not happen, and retval is still a perfectly normal default-constructed vector that you can use freely. So in that example, retval is not assigned to and retval is not printed, because extract_networking threw an exception and execution jumped into the catch block before those two things could happen.