如何在我的while循环中捕获异常

时间:2019-01-18 08:47:00

标签: c# for-loop try-catch do-while

我的问题是,在捕获到第一个异常之后,变量number已经具有一个非零的值,因此当抛出第二个异常时。它只是跳出了我的do-while循环。我希望能够捕获两个或多个异常,具体取决于用户输入,而不会使其跳出循环。

有什么想法吗?我是编码的新手,希望您可以保持简单:)

int number = 0;
int svar = 2; // set by the user; for example 2

do
{
    try
    { 
       for (int i = 0; i < svar; i++)
       {
           Console.Write("\nWrite the number you would like to add to your list: ");
           nummer = int.Parse(Console.ReadLine());
       }

    }
    catch
    {
        Console.WriteLine("\n-- ERROR --");
        Console.WriteLine("You typed a letter instead of a number, try again!");
    }

    myList.Add(number);

} while (number == 0);

4 个答案:

答案 0 :(得分:2)

让代码保持简单 -让我们提取方法 InputInteger;另一个建议是使用TryParse代替异常捕获

   private static int InputInteger(string title) {
     Console.WriteLine(); 

     // Keep on asking user
     while (true) {
       if (!string.IsNullOrEmpty(title)) 
         Console.Write(title);

       // if correct integer value provided, return it
       if (int.TryParse(Console.ReadLine(), out var result)) 
         return result;

       // in case of syntax error print the message
       Console.WriteLine("-- ERROR --");
       Console.WriteLine("Please, type integer number, try again!");
     }
   }  

然后您可以在需要用户输入整数值的任何时候使用它:

   int svar = InputInteger("How many items would you like to have in the list?");

   ...

   // get svar integer items 
   for (int i = 0; i < svar; ++i)
     myList.Add(InputInteger("Write the number you would like to add to your list: ")); 

答案 1 :(得分:1)

您可以使用int.TryParse,请参见下面的示例

 for (int i = 0; i < svar; i++)
 {
     Console.Write("\nWrite the number you would like to add to your list: ");
     while (!int.TryParse(Console.ReadLine(), out number))
     {
         Console.WriteLine("\n-- ERROR --");
         Console.WriteLine("You typed a letter instead of a number, try again!");
     }

     myList.Add(number);
 }

答案 2 :(得分:0)

您需要像这样在其中使用try块

  int number = 0;
int svar = set by the user for exempel 2

do
{

       for (int i = 0; i < svar; i++)
       {
 try
  {
       Console.Write("\nWrite the number you would like to add to your list: ");
       nummer = int.Parse(Console.ReadLine());
   }

   catch
   {
   Console.WriteLine("\n-- ERROR --");
   Console.WriteLine("You typed a letter instead of a number, try again!");
   }

   myList.Add(number);

   }

} while (number == 0);

答案 3 :(得分:0)

感谢您是编码新手。欢迎使用,希望您喜欢。

我对代码进行了一些重构,以使其更简单且没有错误:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ProcessNumbers();
        }

        private static void ProcessNumbers()
        {
            var myList = new List<int>();
            string sinput = String.Empty;
            var number = 0;
            do
            {
                try
                {
                    Console.Write("Write the number you would like to add to your list (type stop when you are done): ");
                    var input = Console.ReadLine();

                    if(input != "stop")
                    {
                        number = int.Parse(input);
                        myList.Add(number);
                    }
                    else
                    {
                        sinput = input;
                    }
                }
                catch
                {
                    Console.WriteLine("ERROR: You typed a letter instead of a number, try again!");
                }

            } while (sinput != "stop");

            var sum = myList.Sum();
            Console.WriteLine("The sum of all your numbers is: " + sum);
            Console.Write("Press any key to exist...");
            Console.ReadKey();
        }
    }
}

基本上,它将持续要求用户保持输入数字,直到用户键入停止为止。最后,它将显示所有数字的总和。如果您对代码有任何疑问,请告诉我。