3

In the process of writing a special collection I utilized the already exisiting IndexOutOfRangeException as e.g. a list or array would throw if I were to access an illegal index. Code analysis tells me, however, that this exception should never be thrown by user code, and I fail to see why. If I were to hand out references to this class abstracted by an interface, for example, wouldn't it be a lot better if it just confirmed to the (perceived) norm of throwing the known and beloved IndexOutOfRangeException than a custom IndexNotInRangeException? What's the motivation behind this rule?

8

IndexOutOfRangeException and NullReferenceException should be thrown by the runtime.

If method, which includes an indexer, validates its parameters, it should throw ArgumentOutOfRangeException and ArgumentNullException instead.

The built in collections, such as List<T> do this:

Exceptions:

ArgumentOutOfRangeException -- index is less than 0. -or- index is equal to or greater than Count.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.