Throwing an ArgumentNullException in the constructor?

For a constructor with a single parameter, is it okay to throw an ArgumentNullException inside the constructor if the parameter is null / empty? OR, should it be cast in a method that actually uses an argument? Thank.

+48
null constructor c # exception arguments
02 Sep 2018-10-18T00:
source share
4 answers

Yes, if absolutely necessary, then throw an exception. You should not * throw an exception later.

Always remember the Fail Early Principle . The concept now does not work, so you do not waste time debugging or experiencing unexpected system functions.

Alternatively, you can also throw an ArgumentException for "" and an ArgumentNullException for null. In any case, make sure you select a valid exception message.




Always a good reference article for managing exceptions: Good rules for managing thumb exceptions




Side note on what @Steve Michelotti said (because I'm a big fan of CodeContracts)

Contract.Requires<ArgumentNullException>(inputParemeter!= null, "inputparameter cannot be null"); Contract.Requires<ArgumentException>(inputParemeter!= "", "inputparameter cannot be empty string"); 

as an alternative

 Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(inputParemeter), "inputparameter cannot be null or empty string"); 
+50
02 Sep '10 at 18:07
source share

Throwing it in the constructor is fine - there are several classes in the .NET Framework. Also, check out the code contracts for this.

+17
Sep 02 '10 at 18:07
source share

From what this sounds, you pass a parameter to the constructor, which will be held by the class for use in another method later. If you are not actually using an argument in the constructor, you should probably consider wrapping the argument as a parameter to the method that actually uses it.

+4
Sep 02 '10 at 18:07
source share

I would put a check in the property that you set when the constructor is called ... Thus, an exception will be thrown in all cases.

+1
02 Sep '10 at 18:07
source share



All Articles