C#中如何捕捉索引超出範圍異常?

WBOY
發布: 2023-08-25 22:13:09
轉載
1786 人瀏覽過

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 &minus;Index was outside the bounds of the array.
登入後複製

以上是C#中如何捕捉索引超出範圍異常?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!