C#输入非整数时仍出现未处理异常求助(已尝试TryParse)
问题分析与修复方案
你的代码现在有两个关键问题导致异常依然会触发,而且逻辑不对:
- 你先执行了
int age = Convert.ToInt32(Console.ReadLine());,这一步只要输入非数字就会直接抛出异常,根本走不到后面的int.TryParse判断 - 后面的
int.TryParse又调用了一次Console.ReadLine(),等于让用户连续输入两次内容,逻辑完全错误
下面是修正后的代码,既可以避免异常,又能循环直到用户输入有效的年龄,后续也能正常使用age变量:
// ask age Thread.Sleep(2000); Console.WriteLine("(OwO) How old are you? (answer only in number pleaseee)"); int age; // 循环直到用户输入有效的数字 while (!int.TryParse(Console.ReadLine(), out age)) { Thread.Sleep(2000); Console.WriteLine("(-w-)"); Thread.Sleep(2000); Console.WriteLine("(-w-) I've told you to only answer in number"); Thread.Sleep(2000); Console.WriteLine("(-w-) You are lucky my developer knows how to include a code to prevent unhandled exception."); Thread.Sleep(2000); Console.WriteLine("(ᗒᗣᗕ) Otherwise that would have crashed me!!!!"); Thread.Sleep(2000); Console.WriteLine("(-w-) Again, how old are you? (don't forget to answer in number)"); } // 这里可以正常使用age变量,比如输出验证 Thread.Sleep(2000); Console.WriteLine($"(UwU) Got it! You're {age} years old!");
代码说明
- 先声明
int age变量,不需要提前赋值,out参数会帮我们初始化 - 使用
while循环,每次读取用户输入并尝试转为整数:- 如果转换失败(输入非数字),进入循环体输出提示,然后再次等待用户输入
- 如果转换成功,退出循环,此时
age已经是有效的整数,后续代码可以直接使用
内容的提问来源于stack exchange,提问作者David McTravord
相关产品推荐
相关产品推荐

