7

FxCop issues a violation of rule CA2201 if you throw System.IndexOutOfRangeException in your code (see reference). The rationale for this is that System.IndexOutOfRangeException is "reserved and should be thrown only by the common language runtime" according to the documentation.

But what can actually go wrong if you throw System.IndexOutOfRangeException?

Paul Jansen
  • 1,216
  • 1
  • 13
  • 35
  • 7
    Why would you ever need to throw it yourself? – Oded Feb 12 '13 at 13:50
  • @Oded When you're implementing low level data structures. – Dustin Kingen Feb 12 '13 at 13:50
  • 4
    @Romoku - Even then. With most types you would have underlying storage in an existing type that will already throw this. – Oded Feb 12 '13 at 13:51
  • 4
    The documentation on the IndexOutOfRangeException explicitly says that it's specific to arrays, so when it's thrown, the user will start looking for an array. If an argument is out of range, it's usual to throw an ArgumentOutOfRangeException. – dtb Feb 12 '13 at 13:53
  • @Oded If you want to create your own index property, which checks whether your index is out of range. – Paul Jansen Feb 12 '13 at 13:54
  • 1
    Even though it can and will work just fine, there is an implicit assumption that the runtime is throwing this exception rather than your code. This may not seem significant, but when you or someone else has to troubleshoot this issue months or years down the road it could lead someone down the wrong path. – Ryan Gates Feb 12 '13 at 14:42
  • The exception to this rule is with Indexers: Indexers are meant to look and act exactly like arrays -- but FxCop reports the same warning. (This is clearly a bug in FxCop that it doesn't realize your method is an indexer. Though some will argue it's not and point you to articles they misread on MSDN.) Even the example code for indexers (has been up on MSDN since 2003) shows it throwing an IndexOutOfRange exception. -- Also lots of regular methods in MS released libraries (some in the framework, some not) throw it (even having not encountered it themselves). – BrainSlugs83 Dec 12 '13 at 20:51

1 Answers1

4

Nothing.

From a technical point of view it is perfectly fine to throw this exception. Nothing will break if you do.

But keep in mind that you should throw the System.IndexOutOfRangeException only if you have encountered a System.IndexOutOfRangeException the first place, because otherwise this exception would not be appropriate as it is very clearly defined what this exception type is to be used for. MSDN states for the System.IndexOutOfRangeException:

The exception that is thrown when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be inherited.

Spontifixus
  • 6,570
  • 9
  • 45
  • 63