4

我有这个具有以下一般结构的 C++ 程序

1st while (condition A == true)
  //some code for 1st loop

  2nd while (condition B == true)
    //some code for 2nd loop
    try
      //some code for try
    catch
      //condition B == false (supposed to leave 2nd loop and go back to first loop)

我希望它在出现异常时退出第二个循环并返回到第一个循环,直到条件 B 再次星期二。如上所述,它不像我预期的那样工作。似乎正在发生的事情是代码被卡住catch并且永远不会离开它。

我该如何安排它以使其按需要工作?

注意:条件 A 永远不会为假。

4

4 回答 4

7

将 break 关键字添加到 catch

还要注意你有 b == false; 那是检查 b 是否等于 false,而不是设置 b = false。

于 2012-08-31T21:59:57.280 回答
2
bool flag1 = true, flag2 = true;
while (flag1)
{
  // some work so that flag2 == true
  while (flag2)
  {
    try
    {

    }
    catch (...) // any exception happens
    {
        break;
    }
  }
}
于 2012-08-31T22:04:05.653 回答
0
1st while (condition A == true) 
  //some code for 1st loop 

  2nd while (condition B == true) 
    //some code for 2nd loop 
    try 
      //some code for try 
    catch 
    {
      //condition B == false (supposed to leave 2nd loop and go back to first loop) 
      break ;
    }

注意:即使在示例中,也请不要使用condition A == true. 最好使用while (condition A).

于 2012-08-31T22:06:44.097 回答
0

您可以在 catch 块中调用 break 来逃避第二个循环:

void foo(void) {
    bool A(true);
    while (A) {
        bool B(doSomething());
        while (B) {
            try {
                B = doSomethingElseThatMayThrow();
            } catch (...) {
                break;
            }
        }
     }
}

或者,您可以将第二个循环放在 try 块内:

void foo(void) {
    bool A(true);
    while (A) {
        bool B(doSomething());
        try { 
            while (B) {
                B = doSomethingElseThatMayThrow();
            }
        } catch (...) {}
    }
}
于 2012-08-31T22:34:30.010 回答