简体   繁体   中英

Throwing ArgumentNullException in constructor?

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

Yes, if it is completely essential then throw the exception. You should not* throw the exception later.

Always remember the "Fail Early Principle" . Concept being fail now, so you don't waste time debugging or experience unexpected system functionality.

Alternatively you could also throw a ArgumentException for "" and ArgumentNullException for null. In either case make sure you throw a valid Exception message.


Always a good reference article for managing exceptions: Good Exception Management Rules of Thumb


Side note on what @Steve Michelotti said (because i am a huge fan of CodeContracts)

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

alternatively

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

Throwing it in the constructor is fine - there are several classes in the .NET framework that do this. Additionally, check out code contracts for this.

From what it sounds like, you pass in a parameter into the constructor to be held by the class for use in some other method later on. If you're not actually using the argument in the constructor, you should probably think about moving the argument to be a parameter of the method that's actually using it.

我将检查放在您调用构造函数时设置的属性中......这样就会在所有情况下抛出异常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM