如何捕获 C# 中的索引超出范围异常?


当你尝试访问超出数组范围的元素时,就会出现 IndexOutOfRangeException 异常。

假设以下为我们的数组。它有 5 个元素 −

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

现在,如果你尝试访问索引超过 5 的元素,那么就会抛出 IndexOutOfRangeException 异常 −

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.

更新时间:2020 年 6 月 20 日

2K+ 浏览量

开启你的 职业生涯

完成该课程获得认证

开始
广告
© . All rights reserved.