Saleh Feek
Saleh Feek

Reputation: 2076

loop input request until valid number accepted

This code is simply throw exception, because short sNum is assigned big range value of int num, and conversion fail. Any way. I want to loop request until valid rang of short is entered.

    static void Main()
    {
        int num = 40000;
        short sNum = 0;
        try
        {
            sNum = Convert.ToInt16(num);

        }
        catch (OverflowException ex)
        {
            // Request for input until no exception thrown.
            Console.WriteLine(ex.Message);
            sNum = Convert.ToInt16(Console.ReadLine());
        }

        Console.WriteLine("output is {0}",sNum);
                        Console.ReadLine();
    }

Thank you.

Upvotes: 0

Views: 1355

Answers (2)

Zaid Masud
Zaid Masud

Reputation: 13443

short sNum;
string input;

do
{
    input = Console.ReadLine();
} while (!Int16.TryParse(input, out sNum))

Console.WriteLine("output is {0}", sNum);

Upvotes: 0

psubsee2003
psubsee2003

Reputation: 8741

The reason is you are throwing an exception when the conversion fails inside your catch block. The catch block technically is outside of the try block, so it will not get caught by the same catch as you seem to think. This is not really behaving as a loop as you appear to hope it will.

Exceptions are not generally considered the best method for normal (non-exceptional) events in your code. The TryParse method and a loop would be much better in this case.

static void Main()
{
    string input = //get your user input;
    short sNum = 0;

    while(!short.TryParse(input,out sNum))
    {
        Console.WriteLine("Input invalid, please try again");
        input = //get your user input;
    }

    Console.WriteLine("output is {0}",sNum);
    Console.ReadLine();
}

Upvotes: 6

Related Questions