0

I have this code:

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!");
            }
        }

I need to handle errors using try-catch when the user doesn't enter any character or enters a non-integer character. How can that be done?

  • 2
    Why don't use `int.TryParse` here? See https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse – Dennis Dec 19 '18 at 09:09
  • 1
    Not with try/catch. Validate the user-input before trying to find the student, and display an error message if validation fails. Only call FindStudent if the input is valid. – Lennart Dec 19 '18 at 09:09
  • Handle `ArgumentNullException` and/or `FormatException` in separate `catch` blocks. Or, a better approach, follow the ideas on the comments above and use `int.TryParse` to validated the input before trying to use it. – Lucas Araujo Dec 19 '18 at 09:14
  • Possible duplicate of [Parse v. TryParse](https://stackoverflow.com/questions/467613/parse-v-tryparse) – mjwills Dec 19 '18 at 09:51

2 Answers2

1

Use TryParse to check if the input is an integer or not. Then if it's an integer, do whatever you want with the index.

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
    }
}
currarpickt
  • 2,290
  • 4
  • 24
  • 39
0

You need to move your int.Parse line inside the try {} block. Only then will it be in the safety net of structured exception handling. You can then add a second catch {} block against a 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.");
    }
}
Ryan
  • 491
  • 4
  • 16