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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)