Open In App

C# | Array IndexOutofRange Exception

C# supports the creation and manipulation of arrays, as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the C# throws an System.IndexOutOfRange Exception. This is unlike C/C++ where no index of the bound check is done. The IndexOutOfRangeException is a Runtime Exception thrown only at runtime. The C# Compiler does not check for this error during the compilation of a program.

Example:




// C# program to demonstrate the 
// IndexOutofRange Exception in array
using System;
  
public class GFG {
      
    // Main Method
    public static void Main(String[] args)
    {
        int[] ar = {1, 2, 3, 4, 5};
          
        // causing exception
        for (int i = 0; i <= ar.Length; i++)
            Console.WriteLine(ar[i]);
    }
}

Runtime Error:



Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at GFG.Main (System.String[] args) in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at GFG.Main (System.String[] args) in :0

Output:



1
2
3
4
5

Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum value of index can be 4 but in our program, it is going till 5 and thus the exception.

Let’s see another example using ArrayList:




// C# program to demonstrate the 
// IndexOutofRange Exception in array
using System;
using System.Collections;
  
public class GFG {
      
    // Main Method
    public static void Main(String[] args)
    {
          
        // using ArrayList
        ArrayList lis = new ArrayList();
        lis.Add("Geeks");
        lis.Add("GFG");
        Console.WriteLine(lis[2]);
    }
}

Runtime Error: Here error is a bit more informative than the previous one as follows:

Unhandled Exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.get_Item (Int32 index) in :0
at GFG.Main (System.String[] args) in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.get_Item (Int32 index) in :0
at GFG.Main (System.String[] args) in :0

Lets understand it in a bit of detail:

The correct way to access array is :

for (int i = 0; i < ar.Length; i++) 
{
}

Handling the Exception:


Article Tags :
C#