我有以下代码:
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处理错误。那怎么办?
最佳答案
使用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
}
}
关于c# - C#-如何使用try-catch block 处理此代码中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53847813/