I have this method to find an object in a list in C++.
Step Config::getStep(string stepName)
{
for(int i=0; i<_NoSteps; i++)
{
if(_Steps[i].getStepNameStr().compare(stepName)==0)
{
return _Steps[i];
}
}
cout << "ERROR. No processing step found for: " << stepName << endl;
// case 1: throw exception
// case 2: return null
}
I got an error while compiling: ‘not all control paths return a value’ as I set it ‘treated warning as error’
I would like to know how to:
-
how to throw a custom exception if there is no object found
-
how to return a NULL object in C# like: return null
Thanks in advance.
You can either return a pointer to an object, or a reference. In C++, unlike C#, you return the object by value, therefore, the object gets copied. To return it by reference, write
Step& Config::getStep(string stepName).To throw an exception, just write
throw MissingStepException();and then handle it like this:You need to define
MissingStepExceptionclass first, of course.Choosing what to do in general: return
NULLor throw exception depends on your logic: if missing step is a logic error or an unlikely condition, it’s better to use exception, otherwise returning aNULLpointer would do.