【发布时间】:2019-10-24 13:51:38
【问题描述】:
我有一个简单的程序,它从用户那里获取一个数字并返回位于数组中该位置/索引处的数字。但是,如果给定的数字不在索引范围内,则会引发异常。 这是我的代码:
int[] arr = { 1, 2, 3, 4, 5, 6 };
Console.WriteLine("input int");
int k = int.Parse(Console.ReadLine());
Console.WriteLine("before");
try
{
double n = 5 / k;
Console.WriteLine(n);
int l=arr[k];
Console.WriteLine(l);
}
catch (DivideByZeroException)
{
throw new ArgumentException("you cant divid by 0!");
}
catch (ArgumentOutOfRangeException)
{
throw new ArgumentException("please give a number between 0-5");
}
catch (Exception)
{
throw new ArgumentException("something went worng, please try again");
}
finally
{
Console.WriteLine("after");
Console.WriteLine("process compited!");
}
但问题是,如果输入的数字是 7,不在范围内,就会显示 ArgumentOutOfRangeException 异常。 如果我希望异常类似于“请给出一个 0-5 之间的数字”,我应该怎么做? (使用try-catch方法)
【问题讨论】:
标签: c# try-catch expectations