在构造函数中抛出ArgumentNullException? [英] Throwing ArgumentNullException in constructor?
问题描述
是的,如果完全是必要的,那么抛出异常。你不应该*稍后抛出异常。
始终记住Early Early Principle 。概念现在失败了,所以你不要浪费时间调试或体验意想不到的系统功能。
或者你也可以为和ArgumentNullException为null抛出一个ArgumentException。在任一情况下,请确保您抛出一个有效的异常消息。
总是一个很好的参考文章,用于管理异常:拇指的异常管理规则
关于@Steve Michelotti所说的话(因为我是CodeContracts的巨大粉丝)
Contract.Requires< ArgumentNullException>(inputParemeter!= null,inputparameter不能为null);
Contract.Requires< ArgumentException>(inputParemeter!=,inputparameter不能为空字符串);
或
Contract.Requires< ArgumentNullException>(!string.IsNullOrEmpty(inputParemeter),inputparameter不能为null或空字符串);
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");
这篇关于在构造函数中抛出ArgumentNullException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!