Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 범위를 벗어난 인덱스를 캡처하는 방법은 무엇입니까?

<시간/>

IndexOutOfRangeException은 배열 범위를 벗어난 인덱스가 있는 요소에 액세스하려고 할 때 발생합니다.

다음이 우리의 배열이라고 가정해 봅시다. 5개의 요소가 있습니다 -

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

이제 인덱스가 5보다 큰 요소에 액세스하려고 하면 IndexOutOfRange 예외가 발생합니다. -

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

위의 예에서는 인덱스 5 위의 액세스를 시도하므로 다음 오류가 발생합니다. -

System.IndexOutOfRangeException:인덱스가 배열 범위를 벗어났습니다.

다음은 전체 코드입니다 -

예시

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

코드는 오류를 생성합니다 -

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