循环输入请求,直到接受有效数字

Sal*_*eek 0 c# loops request

这段代码只是抛出异常,因为短的sNum被分配了int num的大范围值,并且转换失败.无论如何.我想循环请求,直到输入有效的rang of short.

    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();
    }
Run Code Online (Sandbox Code Playgroud)

谢谢.

psu*_*003 5

原因是当您在catch块内转换失败时,您将抛出异常.该catch块在技术上位于块之外try,因此它不会catch像您想象的那样被捕获.这并不像你希望的那样表现为循环.

通常不会将异常视为代码中正常(非异常)事件的最佳方法.TryParse在这种情况下,方法和循环会好得多.

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();
}
Run Code Online (Sandbox Code Playgroud)