开发者

Exception to throw when expecting a null value?

开发者 https://www.devze.com 2023-01-10 15:15 出处:网络
If I am expecting a null value and get a defined va开发者_JS百科lue (within a getter of a property) and want to throw an exception, what would be the proper way to do this in csharp? Is there anything

If I am expecting a null value and get a defined va开发者_JS百科lue (within a getter of a property) and want to throw an exception, what would be the proper way to do this in csharp? Is there anything defined already that makes sense in this situation?


My guess would be:

throw new
    ArgumentException("Parameter was expected to be null, value was provided.");

ArgumentOutOfRangeException might also work, but is typically used when there is a well defined range rather than null vs. not null.


I would probably use ArgumentOutOfRangeException


I've seen InvalidOperationException used, as in the context of trying to set something twice. For example,

if(displayMessage != null)
  throw new InvalidOperationException("The display message may not be set more than once.");

displayMessage = myAwesomeMessage;
0

精彩评论

暂无评论...
验证码 换一张
取 消