List <int> </int>中用户输入的错误处理

时间:2013-08-07 13:57:14

标签: c# list oop error-handling

我有以下代码:

       List<int> moneys = new List<int>();
       Console.WriteLine("Please enter the cost of your choice");
       int money = int.Parse(Console.ReadLine());
       moneys.Add(money);

如果您输入文本,则程序将停止工作,并显示未处理的异常消息。我想知道如何处理异常,如果它甚至可能使程序不停止工作?

5 个答案:

答案 0 :(得分:5)

您应该使用TryParse方法。如果输入无效,它不会抛出异常。这样做

int money;
if(int.TryParse(Console.ReadLine(), out money))
   moneys.Add(money);

答案 1 :(得分:2)

int money ;
bool pass = int.TryParse(Console.ReadLine(), out money);
if(pass)
       moneys.Add(money);

答案 2 :(得分:0)

实施try-catch阻止或使用Int32.TryParse

答案 3 :(得分:0)

要在抛出异常后处理异常,请使用try / catch块。

try
{
//input
}
catch(Exception ex)
{
//try again
}

您也可以使用TryParse预先处理它,并检查int是否为null。

答案 4 :(得分:0)

int.Parse是在解析字符串时无法抛出异常的。你有两个选择:

1)使用Try / Catch处理异常

try {
    int money = int.Parse(Console.ReadLine());
    moneys.Add(money);
} catch {
    //Did not parse, do something
}

此选项可以更灵活地处理不同类型的错误。您可以扩展catch块以分割输入字符串中的3个可能错误,并使用另一个默认catch块来处理其他错误:

} catch (ArgumentNullException e) {
    //The Console.ReadLine() returned Null
} catch (FormatException e) {
    //The input did not match a valid number format
} catch (OverflowException e) {
    //The input exceded the maximum value of a Int
} catch (Exception e) {
    //Other unexpected exception (Mostlikely unrelated to the parsing itself)
}

2)使用int.TryParse返回truefalse,具体取决于是否解析字符串,并将结果发送到第二个参数中指定的变量(out 1}}关键字)

int money;
if(int.TryParse(Console.ReadLine(), out money))
    moneys.Add(money);
else
    //Did not parse, do something