C# - 如何在此代码上为非数字创建例外?

时间:2015-12-28 00:09:41

标签: c# exception-handling int

我想创建一个异常,当我输入一个非数字字符时,最好使用此代码中的Try / catch。我尝试使用int.TryParse,但是当我使用非数字字符时,它只返回0。但是不要向我显示任何错误消息,但是使用int.Parse(Console.ReadLine)我收到一条错误消息:

  

输入字符串的格式不正确。

代码

while (true)
{         
    Console.WriteLine("TYPE A NUMBER HIGHER THAN 20: ");
    int number;
    number = int.Parse(Console.ReadLine());
    if (number> 20)
    {
        Console.WriteLine("O NÚMERO DIGITADO FOI: " + number);
        break;
    }

    else
    {
        Console.WriteLine(number+ " é menor do que 20, favor digitar um número maior");

    }              
}    
Console.ReadLine();

2 个答案:

答案 0 :(得分:0)

您可以像这样创建一个例外:

Console.WriteLine("Type a number: ");
string line = Console.ReadLine();
    try {
        num = Int32.Parse(line);
    } 
    catch (FormatException) {
        Console.WriteLine("{0} is not an integer", line);
    }

或者你可以像你提到的那样使用int.TryParse

Console.WriteLine("Type a number: ");
string line = Console.ReadLine();
if (!int.TryParse(line, out num)) {
    Console.WriteLine("{0} is not an integer", line);
}

答案 1 :(得分:0)

您应该尝试使用Int32.TryParse(而不是Parse)处理输入,而不是抛出异常:

bool run = true;
while (run)
{
    Console.Write("Type in a number: ");
    string input = Console.ReadLine();

    //Exit application
    if(input == "exit")
    {
        run = false;
        return;
    }

    //Returns true if numberStr can be parsed to an int
    int number;
    if (Int32.TryParse(input, out number))
    {
        //input is a number, now let's do some logic!
        if(number > 20)
            Console.WriteLine("Number is greater than 20!");
        else
            Console.WriteLine("Number is less than 20!");
    }
    else
        Console.WriteLine("Doesn't seem to be a number: " + number);

}

Console.ReadLine();