Home > Enterprise >  Throwing custom exception in console application
Throwing custom exception in console application

Time:07-11

so I'm trying to catch a custom exception. It works fine but skips to the next line of the code without giving me a chance to retry. If I try it without a try-catch block it still works but terminates the program. I'd like for it to catch the custom exception then allow me to enter the correct input value. Thanks

Console.WriteLine("Please enter User Name: ");

        try
        {
            
            user.userName = Console.ReadLine();
            
            if(user.userName != "Papa")
            {
                throw new ArgumentException("User name doesn't exist");
            }
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }



       try
        {
            Console.WriteLine("Please enter User Pin: ");
            user.userPin = Convert.ToInt32(Console.ReadLine());

        }

        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

CodePudding user response:

'try' does not mean 'keep trying until no exception'. It just means 'do this and if there is an exception go there'. You have to write a loop yourself

while (true) //loop till 'break'
{ 
    try
    {
        user.userName = Console.ReadLine();
        if (user.userName != "Papa")
        {
            throw new ArgumentException("User name doesn't exist");
        }
        break; //input is good - so break out of loop
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

I would also say that I really dont like using an exception like that, to take a different logic path in side a single function. I would do

while (true)
{
    user.userName = Console.ReadLine();
    if (user.userName == "Papa")
    {
        break;
    }
    Console.WriteLine("Bad user name");
}

CodePudding user response:

You shouldn't use exceptions to control program flow. For your throw new ArgumentException("User name doesn't exist"); you should just write Console.WriteLine("User name doesn't exist");. Avoid exception handlers where possible. They hide actual errors, make your program slow, and make understanding your program more difficult.

Here's how I would write your code to avoid exception handlers:

while (true)
{
    Console.WriteLine("Please enter User Name: ");
    user.Name = Console.ReadLine();
    if (user.Name == "Papa")
    {
        break;
    }
    Console.WriteLine("User name doesn't exist");
}

while (true)
{
    Console.WriteLine("Please enter User Pin: ");
    if (int.TryParse(Console.ReadLine(), out int pin))
    {
        user.Pin = pin;
        break;
    }
    Console.WriteLine("Incorrect Pin");
}
  • Related