运行C#程序触发Format Exception,请求排查代码错误
Hey there! Let's break down why you're hitting that FormatException with the message Input string was not in a correct format in your code.
What's Causing the Error?
The issue comes down to how strict int.Parse() and double.Parse() are. These methods will throw an exception immediately if the input string doesn't perfectly match the expected numeric format. Common triggers include:
- Entering non-numeric text (like "thirty" instead of "30" for age, or a typo like "12a34" for ID)
- Using the wrong decimal separator (e.g., typing "5000,50" instead of "5000.50" for salary—most default system cultures use a dot as the decimal point)
- Accidentally leaving an input blank (hitting Enter without typing anything)
- Adding extra characters like spaces, commas, or hyphens to numeric inputs (e.g., "123-4567" for employee ID)
Fixes to Try
Here are the most practical solutions to resolve this and make your app more robust:
1. Use TryParse() Instead of Parse()
TryParse() is safer because it doesn't throw exceptions—instead, it returns a boolean telling you if the conversion succeeded. You can use it to add friendly error messages for users:
Console.Write("Enter your age: "); if (!int.TryParse(Console.ReadLine(), out int age)) { Console.WriteLine("Oops! Please enter a valid whole number for age."); return; // Exit or handle the error appropriately }
2. Add Clear Input Prompts
Let users know exactly what to enter before they type. This reduces accidental invalid inputs. For example, instead of just calling Console.ReadLine(), add a prompt like:
Console.Write("Enter your 8-digit employee ID: "); int id = int.Parse(Console.ReadLine());
3. Handle Regional Format Differences (If Needed)
If your users might use comma as a decimal separator (common in European countries), specify the correct culture when parsing:
using System.Globalization; // Allow comma as decimal separator for salary double salary = double.Parse(Console.ReadLine(), CultureInfo.GetCultureInfo("de-DE"));
Full Robust Example Code
Here's a revised version of your code using TryParse() and clear prompts to avoid the exception:
Console.Write("Enter your name: "); string name = Console.ReadLine(); Console.Write("Enter your age (whole number): "); if (!int.TryParse(Console.ReadLine(), out int age)) { Console.WriteLine("Error: Age must be a valid whole number."); return; } Console.Write("Enter your 8-digit employee ID: "); if (!int.TryParse(Console.ReadLine(), out int id)) { Console.WriteLine("Error: Employee ID must be a valid whole number."); return; } Console.Write("Enter your salary (e.g., 5500.75): "); if (!double.TryParse(Console.ReadLine(), out double salary)) { Console.WriteLine("Error: Salary must be a valid number."); return; } Console.WriteLine($"\nName: {name}"); Console.WriteLine($"Age: {age}"); Console.WriteLine($"Employee ID: {id:D8}"); Console.WriteLine($"Salary: {salary:F2}");
内容的提问来源于stack exchange,提问作者Yaroslav Dokuzov

