Using throw to replace return in C++ non-void functions

  • A+

In C++ functions, is it a good practice to replace return with throw? For example, I have the following code

// return indices of two numbers whose sum is equal to target vector<int> twoSum(vector<int>& nums, int target) {     for(int i=0; i<nums.size()-1; ++i)         for(int j=i+1; j<nums.size(); ++j)         {             if(nums[i] + nums[j] == target) return vector<int>{i, j};         }     // return vector<int>{};     throw "no solution"; } 

The code above compiles with my GCC 7.2.


In C++ functions, is it a good practice to replace return with throw?

Return is not something that can be replaced by a throw in general.

In exceptional cases where you have nothing to return, throwing an exception can be a valid way to exit the function.

Whether it is "good practice", and what case is "exceptional" are subjective. For example, for a search function such as yours, it's hardly a surprise that there might not be a solution, and I would argue that throwing would not be appropriate.

There are often other alternatives to throwing. Compare your algorithm with something like std::string::find that returns the index of the start of a substring. In case where substring does not exist, it returns a "non-value" std::string::npos. You could do the same and decide that the index -1 is returned when a result is not found. There is also a generic way to add non-value representation to a type in cases where none of the existing representations can be reserved for the purpose: std::optional.

P.S. A vector is probably not a good choice for returning a pair of numbers. std::pair might be better, or a custom class if you have good names for the numbers.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: