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;
   }
}

But it mshould be > 0. What to do to notify the user that he is entering incorrect data in the constructor?

+3
source share
3 answers

You can send ArgumentExceptionor add a contract requiringm > 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;
}
+4
source

Although this is inconsistent (especially in C ++), I think the simplest thing to do here is to throw it away ArgumentException.

Microsoft , , , ( ).

+3

C # has official design guidelines for design in the article http://msdn.microsoft.com/en-us/library/ms229060.aspx , and there he says Do throw exceptions from instance constructors if necessary .

I would say to throw an argument exception, as other people have said, but I would use a few caveats that, if you created something one-time inside your object, clear it before throwing an exception.

+2
source

Source: https://habr.com/ru/post/1763234/


All Articles