编写一个程序,引发一个IndexOutOfRangeException异常,并捕捉处理。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace solution_8
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[2];
for (int i = 0; i <= 2; i++)
{
try
{
array[i] = i;
Console.WriteLine("array[{0}]={1},没有引发异常", i, i);
}
catch (Exception e)
{
Console.Write("array[{0}]={1},引发了异常:", i, i);
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("赋值完成,并运行了finally语句块");
}
}
}
}
}

本文提供了一个使用C#编写的程序示例,展示了如何通过编程手段触发并捕获IndexOutOfRangeException异常。程序中定义了一个整型数组并尝试访问超出数组长度的元素,从而引发异常。
4615

被折叠的 条评论
为什么被折叠?



