如何在 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.

更新於:2020-06-20

2K+ 瀏覽量

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告