当您尝试访问索引超出数组范围的元素时,会发生 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.
以上就是C#中如何捕获索引超出范围异常?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。