Checking data in the constructor

I have a constructor that needs to check the transferred data.

public Rational(int m, int n)

If n == 0, I must report this to the user.
I know 3 ways to do this.

1) Just do it return;in coustructor
2) Throw an exception
3) Create a static method that will create an object

r = new Rational();
r = Rational.GetObject(1,2);

What is the best way to validate data in the constructor?

+3
source share
5 answers

You should throw ArgumentOutOfRangeExceptionin the constructor. (Be sure to include the parameter name in addition to the exception message)

Alternatively, you can also create a static method TryCreate:

public static bool TryCreate(int m, int n, out Rational result);

or

public static Rational? TryCreate(int m, int m);

false null, , ; int.TryParse.

+2

, , , , , ArgumentException .

+8

: () , .

+1

System.ArgumentException .

0

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


All Articles