开发者

Incorrect data in Constructor

开发者 https://www.devze.com 2023-01-14 16:23 出处:网络
I have a class class Rational { private int _n; private int _m; public Rational(int n, int m) { _n = n; _m = m;

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

精彩评论

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

关注公众号