在构造函数中抛出 ArgumentNullException?
对于具有单个参数的构造函数,如果参数为 null/空,可以在构造函数内部抛出 ArgumentNullException 吗?或者,应该将其抛出到实际使用参数的方法中吗?谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,如果这是完全必要的,那么抛出异常。您不应该*稍后抛出异常。
永远记住“尽早失败原则”。概念现在失败了,因此您不会浪费时间调试或遇到意外的系统功能。
或者,您也可以针对“”抛出 ArgumentException,针对 null 抛出 ArgumentNullException。无论哪种情况,请确保抛出有效的异常消息。
始终是管理异常的好参考文章:良好的异常管理拇指规则
Side请注意 @Steve Michelotti 所说的内容(因为我是 CodeContracts 的忠实粉丝)
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)
alternatively
将其放入构造函数中就可以了 - .NET 框架中有几个类可以执行此操作。此外,请查看代码合同。
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.
我会将检查放在调用构造函数时设置的属性中......这样在所有情况下都会引发异常。
I'd put the check in the property that you set when the constructor is called... That way the exception would be thrown in all cases.