How to capture index out of range exception in C#?

CsharpProgrammingServer Side Programming

IndexOutOfRangeException occurs when you try to access an element with an index that is outsise the bounds of the array.

Let’s say the following is our array. It has 5 elements −

int [] n = new int[5] {66, 33, 56, 23, 81};

Now if you will try to access elements with index more than 5, then the IndexOutOfRange Exception is thrown −

for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}

In the above example, we are trying to access above index 5, therefore the following error occurs −

System.IndexOutOfRangeException: Index was outside the bounds of the array.

Here is the complete code −

Example

 Live Demo

using System;

namespace Demo {
   class MyArray {
      static void Main(string[] args) {
         try {
            int [] n = new int[5] {66, 33, 56, 23, 81};
            int i,j;
            // error: IndexOutOfRangeException
            for (j = 0; j < 10; j++ ) {
               Console.WriteLine("Element[{0}] = {1}", j, n[j]);
            }
            Console.ReadKey();
         } catch (System.IndexOutOfRangeException e) {
            Console.WriteLine(e);
         }
      }
   }
}

Output

Element[0] = 66
Element[1] = 33
Element[2] = 56
Element[3] = 23
Element[4] = 81
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Demo.MyArray.Main (System.String[] args) [0x00019] in <6ff1dbe1755b407391fe21dec35d62bd>:0

The code will generate an error −

System.IndexOutOfRangeException −Index was outside the bounds of the array.
raja
Published on 10-Aug-2018 06:46:03
Advertisements