为什么第一次尝试时不显示错误消息,但第二次尝试时却正常工作?

Why does the error message not show for the first try, but works fine for the other?

有人能告诉我为什么当用户输入无效数据格式时第一次 try catch 不显示错误消息,即输入整数而不是字符串。如果我输入数字而不是字母,程序只会接受它并继续前进。 另一个 try catch for age 工作正常。

public void add_passenger()
    {
        // Defining variables for name and age to be input
        string name;
        int age;

        //Show message on a clean, new screen
        Console.Clear();
        Console.WriteLine("==> Welcome aboard <==");
        Console.WriteLine(" Please follow instructions to add yourself as a passenger ");
        Console.WriteLine("");
        
        // Ask user to input name
        while (true)
        {
            Console.WriteLine(" Your name: ");
            //Try and catch in case the user inputs wrong format
            try
            {
                name = Console.ReadLine();
                break;
            }
            catch //This doesn't work
            {
                Console.WriteLine(" Wrong input format. Please try again and input a rider.");
                continue;
            }
        }
        
        // Ask user to input age
        while (true)
        {
            Console.WriteLine(" Your age: ");
            //Try and catch in case the user inputs wrong format
            try
            {
                age = Convert.ToInt32(Console.ReadLine());
                break;
            }
            catch
            {
                Console.WriteLine(" Wrong input format. Please write an integer.");
                continue;
            }
        }

        // Search the array for an empty slot to input the new passenger into
        for (int i = 0; i < passengers.Length - 1; i++)
        {
            if (passengers[i] == null)
            {
                passengers[i] = new Passagerare(name, age);
                break;
            }
            else
            {
                continue;
            }
        }

        Console.WriteLine(""); 
        Console.WriteLine(" You have now boarded the bus. Welcome aboard!" );
        Console.ReadKey(true);
    }

第一个 try/catch 块也正常工作。由开发者决定字符串可以包含什么值以使其有效或无效。

就语言而言,“john doe”和“123151”都是有效的字符串(第二个只是数字的字符串表示形式)。请记住,代码对这两者的解释非常不同:

  1. “123151”
  2. 123151

第一个是值为“123151”的字符串。 第二个是值为 123151 的整数。

当您从 console.ReadLine() 函数读取一个字符串变量时,您将得到一个字符串值,无论输入的是什么值。

我的建议是,向前推进,您添加某种程序来验证输入的值是否更像您的程序所期望的值。例如,如果您不希望字符串中包含任何数字,则可以检查字符串中的整数值,如果找到则抛出异常。您甚至可以使用正则表达式来帮助识别整数或其他无效值。