您好,欢迎访问一九零五行业门户网

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] = 66element[1] = 33element[2] = 56element[3] = 23element[4] = 81system.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#中如何捕获索引超出范围异常?的详细内容。
其它类似信息

推荐信息