我有此代码:
else if (number == 5)
{
Console.Write("Student's index: ");
int index1 = int.Parse(Console.ReadLine());
try
{
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
}
当用户不输入任何字符或输入非整数字符时,我需要使用try-catch处理错误。怎么办?
答案 0 :(得分:1)
使用TryParse
检查输入是否为整数。然后,如果它是整数,则对索引执行任何操作。
else if (number == 5)
{
Console.Write("Student's index: ");
var success = int.TryParse(Console.ReadLine(), out int index1);
if (success)
{
//next logic here if the input is an integer
try
{
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
}
else
{
//do something when the input is not an integer
}
}
答案 1 :(得分:0)
您需要将int.Parse
行移到try {}块内。只有这样,它才会处于结构化异常处理的安全网中。然后,您可以针对FormatException see Int32.Parse docs for exceptions thrown.
else if (number == 5)
{
Console.Write("Student's index: ");
try
{
int index1 = int.Parse(Console.ReadLine());
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
catch (FormatException)
{
Console.WriteLine("Error: Index must be a number.");
}
}