c# - C#-如何使用try-catch block 处理此代码中的错误?

标签 c# error-handling try-catch

我有以下代码:

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/

相关文章:

error-handling - 不要停止 HTTP 错误 403

javascript - 可以将 Catch block 留空导致 JavaScript 中的问题

javascript - Try-Catch 不处理 Node 中 https.get 请求的错误

unit-testing - 如何对 try-catch block 进行单元测试?

c# - 将列表作为 XElement 传递以用作 XML 数据类型参数

c# - 为什么 C# 锁不应该用于长时间操作?

azure - 聊天时出现随机 "Sorry, my bot code is having a issue"消息

c# - 在 .Net 中覆盖/处理我自己的类型转换

c# - 获取枚举值作为字符串数组

login - “Evaluate Now, Respond Later”的最佳实践?