如何在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; //错误: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.