对无输入和无效输入实现Try-Catch



我之所以想这么做,是因为我想阻止会使程序崩溃的输入。我试着这样做,但使用未分配的参数total和out参数totalstring和total时出现错误,必须在控件离开当前方法之前进行分配。

private static void Start(out String totalString, out int total) 
    {
        Console.WriteLine("How Many ? (2-4)");
        Console.WriteLine("");
        try
        { totalString = Console.ReadLine();
            total = int.Parse(totalString);

        }
        catch
            {
                Console.WriteLine("");
            }
        bool flag = false;
        if ((total <= 1) || (total > 4)) //loop to reject invaid input
            while (flag == false)
            {
                if ((total <= 1) || (total > 4))
                {
                    Console.WriteLine("Invalid input. How many?");

                    totalString = Console.ReadLine();
                    total = int.Parse(totalString);
                    Console.Clear();
                }
                else if ((total >= 2) || (total <= 4))
                {
                    flag = true;
                }
            }
 Console.Clear();
        Console.WriteLine("Player Numbers :" + total); 
        Console.WriteLine();
        players = new Player[total];
    }
}
}

很抱歉:)

我宁愿使用TryParse而不是Parse:

Terse:

 int total;
 do {
   Console.WriteLine("How Many ? (2-4)");
 }
 while (!(int.TryParse(Console.ReadLine(), out total) && (total >= 2) && (total <= 4)))

健谈:

  int total;
  Console.WriteLine("How Many ? (2-4)");
  while (true) {
    if (!int.TryParse(Console.ReadLine(), out total)) {
      Console.WriteLine("Invalid input. How many?");    
    else if ((total < 2) || (total > 4)) {
      Console.WriteLine("Invalid range. How many?");  
    else
      break;
  }

当您有一个具有out参数的方法时,无论代码采用何种路径,都必须始终为它们赋值。这就是错误消息试图告诉您的内容。

当你有

   try
    { totalString = Console.ReadLine();
        total = int.Parse(totalString);

并且"Console.ReadLine()"抛出错误,则totalStringtotal都未赋值。类似地,当ReadLine成功,但int.Parse失败时,则不分配total

简单的解决方案:在方法开始时分配默认值:

totalString = null;
total = 0;

当一切正常时,这些将被覆盖。

这里有两个改进:

1去掉out参数并返回玩家数组,而不是使用void方法。

2使用do while循环而不是当前代码:

private static IEnumerable<Player> Start() 
{
    do
    {
        Console.WriteLine("How Many ? (2-4)");
        Console.WriteLine("");
        try
        { 
            var totalString = Console.ReadLine();
            var total = int.Parse(totalString);
            if (total >= 1 && total <= 4)
            {
                Console.WriteLine("Number of players :" + total);
                return new Player[total];
            }
        }
        catch
        {
            Console.WriteLine("Invalid input.");
        }
    } while (true)
}

您会收到此错误,因为如果int.Parse()抛出异常,但您在catch块之后仍在使用它,则total从未被分配
为了避免这种情况,请检查total是否为null
Dmitry Bychenko为您提供了一个非常巧妙的替代方案,所以我只想指出您代码中的一些小东西。

  1. Console.ReadLine()已经是一个字符串,这将起作用:

    total = int.Parse(Console.ReadLine);

  2. 您检查total两次,一次在外部if块中,另一次在while循环中。你不必那样做。

  3. 一旦你在循环中进行了第二次解析尝试并输入了无效的内容,就会抛出一个异常,但你没有处理它

  4. 为了您自己的利益,格式化您的代码。

  5. 尽量避免不必要的例外情况。如果抛出异常,应用程序会冻结几秒钟,这既不好看,也不好玩。例如,如果解析尝试失败,则TryParse返回false

最新更新