I'm trying to figure out how I can throw an exception based on the length of an array, but at the same time, be able to return a value if the length is correct
Ex:
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
Ideally, I'd just want the if (opr.Length ...) and IndexOutOfRangeException.. I think I'm using the IndexOutOfRange incorrectly. Is there a way to throw the exception if the array length is not equal to x (can be whatever #), but if it is, return whatever is in it without the try/catch?
Edit: Figured out a part of it: https://stackoverflow.com/a/20580118/2872988
I think you need to throw by like this
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With