C# - 如何使用 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 处理错误。怎么可能呢?


繁华开满天机
浏览 116回答 2
2回答

HUWWW

用于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    }}

翻阅古今

您需要int.Parse在 try {} 块内移动您的行。只有这样,它才会在结构化异常处理的安全网中。然后,您可以针对 FormatException 添加第二个 catch {} 块,请参阅 Int32.Parse 文档以了解引发的异常。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.");    }}
打开App,查看更多内容
随时随地看视频慕课网APP