为错误的数组长度引发异常
本文关键字:异常 错误 数组 | 更新日期: 2024-09-21 01:39:46
我正试图弄清楚如何根据数组的长度抛出异常,但同时,如果长度正确,则能够返回一个值
例如:
public Complex readInput()
{
Complex temp = 0;
try
{
Console.Write("Enter input: ");
string input = Console.ReadLine();
String[] cplx= input.Split(' ');
if (cplx.Length != x)
{
throw new IndexOutOfRangeException("INVALID INPUT ENTRY...");
}
temp = new Complex(Double.Parse(cplx[0]), Double.Parse(cplx[1]), ...);
}
catch (FormatException)
{
Console.WriteLine("INVALID INPUT ENTRY...");
}
return temp;
} // end readInput
理想情况下,我只想要if(opr.Length…)和IndexOutOfRangeException。。我认为我使用IndexOutOfRange不正确。如果数组长度不等于x(可以是任意#),有没有方法抛出异常,但如果是,则返回其中的任意值,而不使用try/catch?
编辑:算出了其中的一部分:https://stackoverflow.com/a/20580118/2872988
我认为你需要像这个一样扔过去
public Complex readInput()
{
Complex temp = 0;
try
{
Console.Write("Enter input: ");
string input = Console.ReadLine();
String[] cplx= input.Split(' ');
if (cplx.Length >= x)
{
throw new IndexOutOfRangeException("INVALID INPUT ENTRY...");
}
temp = new Complex(Double.Parse(cplx[0]), Double.Parse(cplx[1]), ...);
}
catch (FormatException)
{
Console.WriteLine("INVALID INPUT ENTRY...");
}
return temp;
}
Hy,如果使用自己的异常描述,代码会更好一些。尝试使用Exception(字符串描述)。这样代码看起来会更好。请记住,异常是为了提醒程序员某些事情工作不正常。
Complex temp = null;
try
{
Console.Write("Enter input: ");
string input = Console.ReadLine();
String[] cplx = input.Split(' ');
if (cplx.Length != x)
throw new Exception("INVALID INPUT ENTRY...");
temp = new Complex(Double.Parse(cplx[0]), Double.Parse(cplx[1]));
}
catch (Exception)
{
Console.WriteLine("INVALID INPUT ENTRY...");
}