5

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)

Mario The Spoon
  • 4,799
  • 1
  • 24
  • 36

2 Answers2

8

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I have to disagree on calling an indexer's parameter an index being a weak argument. As does MSDN. "Indexers allow instances of a class or struct to be indexed just like arrays." via http://msdn.microsoft.com/en-us/library/vstudio/6x16t2tx.aspx -- so why then, shouldn't an indexer behave like an array? – BrainSlugs83 Oct 20 '13 at 07:17
6

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.

STO
  • 10,390
  • 8
  • 32
  • 32
  • Marc beat you to it though :-) – Mario The Spoon Sep 02 '12 at 17:46
  • Also via MSDN (per my reply to Marc): "Indexers allow instances of a class or struct to be indexed just like arrays." -- so again, if the purpose of an indexer is to emulate an array, why would IndexOutOfRangeException be off limits? – BrainSlugs83 Oct 20 '13 at 07:18
  • That exception is intended to be used in runtime array bounds check (which could be turned off due optimization). But of course you can use it if you would like :) – STO Oct 21 '13 at 09:49