c# - List<int> 中用户输入的错误处理

标签 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);

如果您从这里输入文本,程序将停止工作并出现未处理的异常消息。我想知道您将如何处理异常,如果有可能使程序不停止工作?

最佳答案

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

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

关于c# - List<int> 中用户输入的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18105399/

相关文章:

c# - 如何在文件夹中找到第二个最新文件

python - 如何使用 for 循环索引列表?

python - 如何从两个列表中查找匹配的部分项目

java - 关于继承的Java类的性质的问题

php - $this 的范围在 PHP 中是 funked 是错误还是功能?

php - 在 PHP 中调用父级的构造函数

c# - c# 中 "base"关键字的真正用途是什么?

c# - 如何模拟采用动态对象的方法调用

c# - 这些是什么类型的测试,应该编写它们吗?

python - 如何按相同字段合并字典列表并在此过程中对另一个字段求​​和?