c# - 如何从内部的 try/catch 外部打破循环?

标签 c# while-loop try-catch break

我正在为学校做一个简单的类项目,以试验 c# 中的继承和其他要素,但我在某个部分遇到了问题。我相信我需要在无条件 while 循环中 try catch 以确保用户以正确的形式输入数据,但我还需要能够从错误处理代码中跳出循环。我在给我带来问题的代码下方添加了注释。

class Program : students
{
    static void Main(string[] args)
    {
        students stu = new students();

        Console.Write("Number of students are you recording results for: ");
        int studNum = int.Parse(Console.ReadLine());
        stu.setNoOfStudents(studNum);
        Console.WriteLine();

        for (int a = 0; a < studNum; a++)
        {
            Console.Write("{0}. Forename: ", a + 1);
            stu.setForname(Console.ReadLine());
            Console.Write("{0}. Surname: ", a + 1);
            stu.setSurname(Console.ReadLine());
            while (0 == 0)
            {
                try
                {
                    Console.Write("{0}. Age: ", a + 1);
                    stu.setstudentAge(int.Parse(Console.ReadLine()));
                    Console.Write("{0}. Percentage: ", a + 1);
                    stu.setpercentageMark(int.Parse(Console.ReadLine()));
                    stu.fillArray();

                    break;
                    // This is the block that gives me problems; the
                    // while loop doesn't break.
                }

                catch (Exception)
                {
                    Console.WriteLine("This must be a number.");
                }
            }
        }
    }
}

我没有收到错误,因为它在 try/catch 中,但 while(0 == 0) 循环从未中断,因此 for 循环无法迭代命令。有人可以给我一个解决方案吗?

最佳答案

试试这个而不是休息

bool stop = false;
while (!stop)
{
    try
    {
        // Time to exit the loop
        stop = true;
     }
     catch { ... }
}

关于c# - 如何从内部的 try/catch 外部打破循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32605517/

相关文章:

c# - 有没有办法计算忽略初始化时间的测试方法的运行时间?

php - 在 PHP 的 while 循环中在偶数和奇数之间交替

While 循环中的 PHP 更新

ios - 在哪里捕获错误(错误 :ErrorType) that are thrown inside Delegate methods in Swift 2. 0

java - 可能的尝试/捕获和内存管理问题?

c# - 如何从此图中获取所有路径?递归?

C# Databound ComboBox 自动更新

c++ - 带有 try catch 和异常抛出的方法

c# - 访问静态代码块内的 "this"

php - 我的数据库中的 while 循环正在重复结果。我知道这是我的查询格式不正确。