开发者

Incorrect data in Constructor

I have a class

class Rational
{
   private int _n;
   private int _m;

   public Rational(int n, int m)
   {
      _n = n;
      _m = m;
  开发者_如何学JAVA }
}

But m should be > 0. What should I do to notify user that he enter incorrect data to constructor?


You could throw an ArgumentException or add a contract requiring m > 0

if(m <= 0) throw new ArgumentException("Denominator must be positive");

or

public Rational(int n, int m)
{
    Contract.Requires(m > 0);
    _n = n;
    _m = m;
}


Although it's controversial (especially in C++), I think the most straightforward thing to do here would be throwing an ArgumentException.

Microsoft guidelines recommend throwing exceptions from constructors when it makes sense, for example if the arguments do not allow creation of a usable object (which is your case).


Within C# there are official constructor design guidelines in the article http://msdn.microsoft.com/en-us/library/ms229060.aspx and in there it says Do throw exceptions from instance constructors if appropriate.

I would say to throw an argument exception as other people have said but I would use a few caveats that if you have created anything that is Disposable within your object, clean up before throwing the exception

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜