'How to return an error message from a fuction?

I have a function in a C++ code which should return a certain type of data (vector in this case, I have the definition typedef Eigen::VectorXd vector from the eigen library) but I have a condition where, if one of the parameters of the fuction is not valid to the kind of data I'm managing, that function should return an error message, I tried

else {cout << "the error message\n"}

With an if-else statement, but, since it does not return a vector but the print in terminal, the compiler is giving me the warning X control may reach end of non-void function every time I compile and it's kinda annoying having that message, Do you have you any idea to get rid that warning? Thank you in advance.

P.S: The code is working, I just want to fix that warning, if you need the implementation of the function please ask for it

c++


Solution 1:[1]

Usually you handle this kind of errors by throwing an exception. here an example:

 Eigen::VectorXd Foo(int p1, int p2)
 {
     .....

     if (!IsParamsValid(p1,p2))
     {
         throw std::invalid_argument("p1 or p2 is invalid");
     }

     .....
 }

Solution 2:[2]

You can just return an empty vector when that error condition occurs. When you get the return value back in the calling function, just check the size of the returned vector and make sure it's not zero.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Spio23
Solution 2 fireshadow52