How to capture index out of range exception in C#?
Answers
Answer:
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
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
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
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 :0
The code will generate an error −
System.IndexOutOfRangeException −Index was outside the bounds of the array.
Explanation: