2

I have added a new class to my library which will be part of the public documented API. The underlying data structure is a native array though List<T> is used when first generating the native array.

The MSDN indicates that List<T> throws ArgumentOutOfRangeException rather than IndexOutOfRangeException (which can be thrown when accessing a native array).

So I plan to update my functions to always throw ArgumentOutOfRangeException for consistency within my documented API like follows:

public class MyClass {
    private int[] _values;

    public int GetValue(int index) {
        if (index < 0 || index >= _values.Length)
            throw new ArgumentOutOfRangeException("index");
        return _values[index];
    }
}

My question is this:

Will the above source incur two range checks (my one + native array one) or is the .NET compiler smart enough to remove the IndexOutOfRangeException checks?

Lea Hayes
  • 62,536
  • 16
  • 62
  • 111
  • Similar post at http://stackoverflow.com/questions/12237487/indexoutofrangeexception-in-indexed-getter and here http://stackoverflow.com/questions/383291/indexoutofrangeexception-for-an-ilistt – makemoney2010 Apr 29 '14 at 22:52
  • 3
    Why bother? I agree that it is odd that they don't use the same exception and perhaps even weirder that the text for `ArgumentOutOfRangeException` says that the index was out of range, but I don't see this adding a lot of value. These exceptions usually indicate a program error that should be fixed. The exception should not be caught and "handled" – Brian Rasmussen Apr 29 '14 at 22:52
  • @sircodesalot Would it make better sense to wrap the access within a `try`...`catch` block to catch the `IndexOutOfRangeException` and throw `ArgumentOutOfRangeException`? – Lea Hayes Apr 29 '14 at 22:52
  • @BrianRasmussen I must say that is a good argument. If you post that as an answer then I will accept it :) – Lea Hayes Apr 30 '14 at 13:48

1 Answers1

2

Why bother? I agree that it is odd that they don't use the same exception and perhaps even weirder that the text for ArgumentOutOfRangeException says that the index was out of range, but I don't see this adding a lot of value.

These exceptions usually indicate a program error that should be fixed. The exception should not be caught and "handled".

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317