Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to handle IndexOutOfRangeException

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 181
    Comment on it

    "Handling IndexOutOfRangeException"

        Before learning how to handle this exception, we should know why this Exception is thrown

    IndexOutOfRangeException:

        This Exception is raised when we are trying to access invalid index in an Array.

    Let us take an Example:

    byte[] array = new byte[4];
    

       The array in C# starts with 0 index therefore we can access it from 0 to 3 index only as the length of the given array is 4. But if we try to access the array outside this range (i.e Less than 0 or Greater than 3) the IndexOutOfRangeException will be thrown.

    We use array.length for calculating the length of the array i.e if we calculate the length of the above array we will get 4 therefore we can say that the first element of the array is on 0 index and the last element is on (length-1) i.e 3 index.

    However we can customize the lower bound of the array but not the upper bound.

    Example:

    var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });
    

    In the above example the lower bound of the array will be 1 i.e. the first element will be on 1 index.

    This Exception is also applied to List:

    Same as in the case of arrays, List also starts with the 0 index to List.Count therefore accessing beyond this range causes this Exception to be raised.

    Also when the List is created it starts Empty therefore accessing the just created List i.e Empty List also causes this Exception to be raised.

    How to avoid this Exception:

    Inorder to avoid this Exception, we have to take care while using upper and lower bounds,

    1. Replace 0 with GetLowerBound(0) and .Length with GetUpperBound(0), For example:

    for (int i=0; i < 4; ++i) 
    {
       //
    }
    

    This code should be replaced by:

    for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) 
    {
      //
    }
    

    This will help not to access invalid indexes.

    2. If the index is coming through some parameters, so it will be better to validate them before accessing the array values.

    Example:

    public void Check(int from, int length)
    {
        if (from < 0 || from >= array.Length)
            throw new ArgumentOutOfRangeException("from");
    
        if (length < 0 || length < from)
            throw new ArgumentOutOfRangeException("length");
    
        for (int i=from; i < length-1; ++i)
            {
                //
            }
    }
    

    3. Incase of increment and decrement check the current index value first, So that it may not go beyond the valid range, as this will lead to the Exception.

    Happy Coding..!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: