Return types when arguments may be valid or invalid?

Hi

I have a library which basically stores a collection of objects, each of which has a unique id.

The library has certain functions which, for example, return a variable in relation to a given object. The argument for such a function would be a unique id.

But what should happen when an object with that id does not exist? Clearly, I cannot return a 'false' bool when the function would return a string if the object does exist. Should I throw an exception here?

Thanks
Depending on the type of data passed back, be it a pointer, an int etc you can return a invalid value such as nullptr , 0 or -1, then test for such when calling the function such as

1
2
3
4
if (SomeFunction == 0)
	{
		std::cout << "SOME ERROR MESSAGE";
	}
Last edited on
yeh, except this won't work if the number could be a 0 or a -1 or for other types (e.g. a string)
Unless you use a parameter to pass the output variable and use the return mechanism to return a status indicator there is really no one elegant way to handle errors other than throwing and catching an exception.

No matter how you intend to solve the problem you should insure that your function's documentation fully describes what happens if the pre or post conditions (and what those pre and post conditions actually are) are not satisfied.


ok thanks

do you think it would be appropriate in my case to throw std::out_of_range?
Possibly, but you may want to consider making your own exception class.

Consider std::optional<T>.
Topic archived. No new replies allowed.