-2

I couldn't find any c# examples in the 30 seconds I spent looking for one, but I have a problem. When a user types a string instead of an integer the console crashes and I cannot for the life of me handle this exception.

    static void Main(string[] args)
    {

        Console.Write("Age: ");
        int Age = Convert.ToInt32(Console.ReadLine());

        Console.ReadKey();

    }
xxxlaf
  • 37
  • 5

2 Answers2

1

you are casting whatever user has typed in console to integer by Convert.ToInt32 without checking whatever user has typed is actaully valid number string or any other alphanumeric string (or pure aplhabatic or special charactors)

you must make sure that user's input is valid numeric or not while casting.

you can use TryParse instead of Convert.ToInt32 for that. like below,

int.TryParse(Console.ReadLine(), out Age);

more interesting, this method returns a boolean too. if conversion is succssfull then it will return true else false. So if your further logic is depandant on Age you can prevent it from performing if user has not entered valid input.

like below.

while(true)
{
    if (int.TryParse(Console.ReadLine(), out Age))
    {
        break;
    }
    else
    {
        Console.WriteLine("Invalid input for age, please enter again");
    }
}
//from here your further logic

I too find for solution for 30 seconds on google, surprisingly i found lot of interesting links

Google

MSDN

https://stackify.com/convert-csharp-string-int/

Is there a try Convert.ToInt32... avoiding exceptions

Amit
  • 1,821
  • 1
  • 17
  • 30
0
static void Main(string[] args)
{
    Try{
    Console.Write("Age: ");
    int Age = Convert.ToInt32(Console.ReadLine());

    Console.ReadKey();
    }
    Catch (Exception e){
    Console.writeLine(e)
    }

}
Christophe Chenel
  • 1,802
  • 2
  • 15
  • 46