Home > Article > Backend Development > How to catch index out of range exception in C#?
IndexOutOfRangeException occurs when you try to access an element whose index is outside the range of the array.
Suppose the following is our array. It has 5 elements -
int [] n = new int[5] {66, 33, 56, 23, 81};
Now if you try to access an element with index greater than 5 then IndexOutOfRange exception will be thrown -
for (j = 0; j < 10; j++ ) { Console.WriteLine("Element[{0}] = {1}", j, n[j]); }
In the above example we are trying to access the above Index 5, so the following error occurs -
System.IndexOutOfRangeException: Index is outside the range of the array.
This is the complete code -
Live demonstration
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); } } } }
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 produce an error-
System.IndexOutOfRangeException −Index was outside the bounds of the array.
The above is the detailed content of How to catch index out of range exception in C#?. For more information, please follow other related articles on the PHP Chinese website!