Home > Enterprise >  Still stuck in unhandled exception when trying to type string in interger in C#
Still stuck in unhandled exception when trying to type string in interger in C#

Time:11-17

so I'm making a "bot" program, when the bot ask you questions and you type the answer. When the bot asking your age, obviously you can't answer other than number. And if you try to insert non-number (eg: daskjldsjal), it will produce unhandled exception. I tried using TryParse, but it still won't work. Here's the code

` //ask age
            Thread.Sleep(2000);
            Console.WriteLine("(OwO) How old are you? (answer only in number pleaseee)");
            int age = Convert.ToInt32(Console.ReadLine());

        if (!int.TryParse(Console.ReadLine(), out age))
        {
            Thread.Sleep(2000);
            Console.WriteLine("(-w-)");
            Thread.Sleep(2000);
            Console.WriteLine("(-w-) I've told you to only answer in number");
            Thread.Sleep(2000);
            Console.WriteLine("(-w-) You are lucky my developer knows how to include a code to prevent unhandled exception.");
            Thread.Sleep(2000);
            Console.WriteLine("(ᗒᗣᗕ) Otherwise that would have crashed me!!!!");
            Thread.Sleep(2000);
            Console.WriteLine("(-w-) Again, how old are you? (don't forget to answer in number)");
        }`

I'm new in any programming, so sorry if this seems so mundane/trivial. Thank you.

I expect it to display the error message (the I've told you etc etc), and I don't think try and catch will work since it has values that will be asked later.

CodePudding user response:

int age = Convert.ToInt32(Console.ReadLine());

is useless and causing the error

add an 'int' to your try parse to make it like this

Thread.Sleep(2000);
Console.WriteLine("(OwO) How old are you? (answer only in number pleaseee)");

if (!int.TryParse(Console.ReadLine(), out int age))
{
    Thread.Sleep(2000);
    Console.WriteLine("(-w-)");
    Thread.Sleep(2000);
    Console.WriteLine("(-w-) I've told you to only answer in number");
    Thread.Sleep(2000);
    Console.WriteLine("(-w-) You are lucky my developer knows how to include a code to prevent unhandled exception.");
    Thread.Sleep(2000);
    Console.WriteLine("(ᗒᗣᗕ) Otherwise that would have crashed me!!!!");
    Thread.Sleep(2000);
    Console.WriteLine("(-w-) Again, how old are you? (don't forget to answer in number)");
}

'Out' keyword dosen't need initialization.

  • Related