【发布时间】:2013-12-14 04:51: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
【问题讨论】:
-
什么是 x ?你需要定义它吗?!
-
x 只是一个数字。你可以在那里输入任何数字,没关系
-
你的代码不能正常工作,x应该被赋值,然后在你的catch块中,你可以添加许多catch,它们有很多异常类型。
-
尝试类似 string Test = cplx[x];那么如果索引不存在,您将得到索引超出范围异常,该异常将由 Catch 处理。