4

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?

asked Nov 3, 2014 at 14:35

1 Answer 1

9

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.

answered Nov 3, 2014 at 14:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.