Как обрабатывать ошибки в этом коде, используя блок try-catch? - PullRequest
0 голосов
/ 19 декабря 2018

У меня есть этот код:

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, когда пользователь не вводит какой-либо символ или вводит нецелочисленный символ.Как это можно сделать?

Ответы [ 2 ]

0 голосов
/ 19 декабря 2018

Вам нужно переместить int.Parse строку внутри блока try {}.Только тогда он окажется в сети безопасности при обработке структурированных исключений.Затем вы можете добавить второй блок catch {} против FormatException , смотрите Int32.Parse docs для исключений.

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.");
    }
}
0 голосов
/ 19 декабря 2018

Используйте 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
    }
}
...