title: Returning NaN or throwing an exception?
body: <p>I have a function that gets a sample (an <code>std::vector&lt;double&gt;</code>) as input and computes the average of the sample: what is the best way to handle the empty input vector case?</p>
  
  <p>My first idea is to throw an exception like in this snippet:</p>
  
  <pre><code>double average(const std::vector&lt;double&gt;&amp; sample)
  {
     size_t sz = sample.size();
     if (sz==0) throw std::exception("unexpected empty vector");
  
     double acc = 0;
     for (size_t i=0; i&lt;sz; ++i) acc += sample[i];
     return acc/sz;
  }
  </code></pre>
  
  <p>But I think another solution could be to return NaN:</p>
  
  <pre><code>double average(const std::vector&lt;double&gt;&amp; sample)
  {
     size_t sz = sample.size();
     if (sz==0) return std::numeric_limits&lt;double&gt;::quiet_NaN();
  
     double acc = 0;
     for (size_t i=0; i&lt;sz; ++i) acc += sample[i];
     return acc/sz;
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>Is there any other way of cope with the empty vector?
  Thank you.</p>