在构造函数中抛出ArgumentNullException? [英] Throwing ArgumentNullException in constructor?
问题描述
对于具有单个参数的构造函数,如果参数为null / empty,是否可以在构造函数内部抛出ArgumentNullException? OR,是否应该在实际使用参数的方法中抛出?感谢。
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.
或者,你也可以抛出一个ArgumentException和ArgumentNullException为null。在任一情况下,请确保您抛出有效的异常消息。
Alternatively you could also throw a ArgumentException for "" and ArgumentNullException for null. In either case make sure you throw a valid Exception message.
始终是一个管理异常的好参考文章: Thumb的异常管理规则
Always a good reference article for managing exceptions: Good Exception Management Rules of Thumb
@Steve Michelotti说的话(因为我是CodeContracts的巨大粉丝)
Contract.Requires<ArgumentNullException>(inputParemeter!= null, "inputparameter cannot be null");
Contract.Requires<ArgumentException>(inputParemeter!= "", "inputparameter cannot be empty string");
或
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(inputParemeter), "inputparameter cannot be null or empty string");
这篇关于在构造函数中抛出ArgumentNullException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!