Is it better allow a function to throw or throw in the constructor?
<p>I think, it is easier explain using an example. Let's take a class that model the speed of a Formula 1 car, the interface may look something like:</p>

<pre><code>class SpeedF1
{
public:
  explicit SpeedF1(double speed);
  double getSpeed() const;
  void setSpeed(double newSpeed);
  //other stuff as unit 
private:
  double speed_;
};
</code></pre>

<p>Now, negative speed are not meaningful in this particular case and neither value greater then 500 km/h. In this case the constructor and the setSpeed function may throw exceptions if the value provide is not within a logical range.</p>

<p>I can introduce an extra layer of abstraction and insert a extra object instead of double.
The new object will be a wrapper around the double and it will be construct and never modify.
The interface of the class will be changed to:</p>

<pre><code>class ReasonableSpeed
{
public:
  explicit ReasonableSpeed(double speed); //may throw a logic error
  double getSpeed() const;
  //no setter are provide
private:
  double speed_;
};

class SpeedF1
{
public:
  explicit SpeedF1(const ReasonableSpeed&amp; speed);
  ReasonableSpeed getSpeed() const;
  void setSpeed(const ReasonableSpeed&amp; newSpeed);
  //other stuff as unit 
private:
  ReasonableSpeed speed_;
};
</code></pre>

<p>With this design SpeedF1 cannot throw, however I need to extra pay an object constructor every time I want to reset the speed.</p>

<p>For class where a limited set of value are reasonable (for example the Months in a calendar) I usually make the constructor private and provide a complete set of static functions. In this case it is impossible, another possibility is implement a null object pattern but I am not sure it is superior to simply throw an exception.</p>

<p>Finally, my question is:</p>

<p>What is the best practise to solve this kind of problem?</p>
