views:

49

answers:

3

I have a class

class Rational
{
   private int _n;
   private int _m;

   public Rational(int n, int m)
   {
      _n = n;
      _m = m;
   }
}

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

+4  A: 

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;
}
Lee
I thought that Exteption in constructor isnt right.
Sergey Gavruk
@Sergey Gavruk Throwing an `ArgumentException` or `ArgumentNullException` in a constructor is perfectly normal, and a practice used in many of the core .net classes.
klausbyskov
@Sergey - There's no reason not to that I'm aware of, as long as no resources (e.g. file handles) are leaked. It's common for BCL classes to do this - if an object cannot be created in a valid state then the only sensible thing it can do is throw an exception.
Lee
+2  A: 

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).

axel_c
+1  A: 

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

Ian Johnson
+1 for guidelines
igor