如何捕獲 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.