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?
m
> 0
You can send ArgumentExceptionor add a contract requiringm > 0
ArgumentException
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 this is inconsistent (especially in C ++), I think the simplest thing to do here is to throw it away ArgumentException.
Microsoft , , , ( ).
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.
Source: https://habr.com/ru/post/1763234/More articles:.htpasswd / .htaccess allows * almost * working with any password - securityinstalling gentoo geoip - linuxGetting multiple requests when making a transaction, why? - nhibernateMake the first successful match in a series of regular expressions - pythonHow to use hg push in Mercurial - windowshow to avoid overlapping edge and node when using graphviz? - graphvizHibernate criteria - exclude groupProperty from the selected - javaClearing bidirectional iterator code - c ++Replacing an array in vim - vimHow can I clear this LINQ query (SelectMany)? - c #All Articles