如何在C#整数输入中兼容"null"字符串并避免未处理异常?
Got it, let's break down why your code is throwing that exception and fix it properly.
The Problem with Your Current Code
When you input "null", Convert.ToInt32(Console.ReadLine()) tries to convert that string to an integer—and since "null" isn't a valid numeric value, it immediately throws a FormatException before your if (age == null) check even runs. That's why you're seeing the unhandled error.
The Fix: Handle Input as a String First
We need to capture the raw input string first, check if it's "null", and only then attempt to convert it to an integer (safely, to avoid other potential errors). Here's a revised version of your code that works as expected:
int? age = null; Console.Write("\nInsert age: "); string userInput = Console.ReadLine(); // Check if the input is exactly "null" (use StringComparison.OrdinalIgnoreCase if you want to accept "Null"/"NULL" too) if (string.Equals(userInput, "null", StringComparison.Ordinal)) { age = null; } else { // Use int.TryParse for safe conversion—no exceptions if input is invalid if (int.TryParse(userInput, out int parsedAge)) { age = parsedAge; } else { // Optional: Handle cases where input is neither "null" nor a valid integer Console.WriteLine("Oops, that's not a valid integer or 'null'. Let's default to empty age."); age = null; } } // Output the result if (age == null) { Console.WriteLine("Your age:"); } else { Console.WriteLine($"Your age: {age}"); }
Key Improvements:
- Raw Input Capture: We first read the input as a string, so we can check for "null" before any conversion attempts.
- Safe Conversion:
int.TryParsereplacesConvert.ToInt32because it returns a boolean indicating success/failure instead of throwing an exception. This makes your code more robust against typos or invalid inputs. - Flexibility: If you want to accept case-insensitive "null" inputs (like "Null" or "NULL"), just swap
StringComparison.OrdinalwithStringComparison.OrdinalIgnoreCasein thestring.Equalscheck.
This code will now:
- Output
Your age:when you input "null" - Output
Your age: [number]when you input a valid integer - Gracefully handle other invalid inputs (with an optional error message) instead of crashing.
内容的提问来源于stack exchange,提问作者James esmenya
相关产品推荐
相关产品推荐

