Exception to throw when expecting a null value?

前提是你 提交于 2019-12-13 15:11:15

问题


If I am expecting a null value and get a defined value (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?


回答1:


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.




回答2:


I would probably use ArgumentOutOfRangeException




回答3:


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;


来源:https://stackoverflow.com/questions/3400818/exception-to-throw-when-expecting-a-null-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!