IndexOutOfRangeException in indexed getter

こ雲淡風輕ζ 提交于 2019-12-10 13:53:37

问题


In my indexed property I check whether the index is out of bounds or not. If it is, I throw an IndexOutOfBoundsException.

When I run the Code Analyst (in VS12) it complains with CA1065: Unexpected exception in unexpected location.

Referring to the description of CA1065, only

System.InvalidOperationException
System.NotSupportedException
System.ArgumentException
KeyNotFoundException

are allowed in an indexed getter.

Throwing IndexOutOfBoundsException seems natural to me, so what is the reasoning here? (And yes, I know I can turn the warning off, I just want to know the reasoning)


回答1:


A lot of classes use ArgumentOutOfRangeException for this, including List<T>. This is a subclass of ArgumentException so should satisfy the rule. I guess you could argue that for a vector etc accessed directly, there isn't actually a method call (it is a dedicated opcode - ldelem*), so the index in that case isn't actually an argument. Seems a weak argument, though.




回答2:


See MSDN: IndexOutOfRangeException is system exception and reserved for accessing array elements. It is thrown by some MSIL instructions: ldelem., ldelema, stelem..

For developing classes use ArgumentOutOfRangeException.



来源:https://stackoverflow.com/questions/12237487/indexoutofrangeexception-in-indexed-getter

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