Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning NaN or throwing an exception?

I have a function that gets a sample (an std::vector<double>) as input and computes the average of the sample: what is the best way to handle the empty input vector case?

My first idea is to throw an exception like in this snippet:

double average(const std::vector<double>& sample)
{
   size_t sz = sample.size();
   if (sz==0) throw std::exception("unexpected empty vector");

   double acc = 0;
   for (size_t i=0; i<sz; ++i) acc += sample[i];
   return acc/sz;
}

But I think another solution could be to return NaN:

double average(const std::vector<double>& sample)
{
   size_t sz = sample.size();
   if (sz==0) return std::numeric_limits<double>::quiet_NaN();

   double acc = 0;
   for (size_t i=0; i<sz; ++i) acc += sample[i];
   return acc/sz;
}

I like the exception because it shows where the problem happened while if I get a NaN in a final result of a long computation I will have more difficulties to understand where the NaN was born. Anyway with the NaN I like the possibility of returning a "special" double to signal something unexpected happened.

Is there any other way of cope with the empty vector? Thank you.

like image 897
Alessandro Jacopson Avatar asked Sep 03 '11 13:09

Alessandro Jacopson


1 Answers

I DO think that mathematically the NaN would be more correct. In the end it's 0.0/0. Had it been a direct division, what would have happened?

Be aware that about C++ and exceptions there are holy wars. For example read this: To throw or not to throw exceptions?

like image 137
xanatos Avatar answered Oct 02 '22 19:10

xanatos