What is the best way to handle invalid function arguments? (I understand there is no sinuglar best way, because it depends on the situation, but read "best" here as "a common practice").
Let's say I have the function
template<typename T> std::pair<T,T> min_max(const T* v, const size_t n){ if(n <= 0){ throw std::invalid_argument("Array of size zero passed as argument."); } T min = v[0], max = v[0]; for(size_t i = 0;i < n;++i){ if(v[i] < min){ min = v[i]; } if(v[i] > max){ max = v[i]; } } return std::make_pair<T,T>(min, max); } which returns a pair containing the smallest and the largest value in the array v. But if the size n is less than or equal to zero, there are no values to extract, so I can't really return anything. Should I throw an exception (like done in this example)?
Thank you.
size_tis an unsigned type. It cannot be less than zero, so you might as well comparetfor equality to zero.try_min_maxand return something likeboost::optional<std::pair<T,T>>. However, then you are burdening the well-behaved callers with extra work to accommodate the badly-behaved ones.