C ++尝试Catch内部循环

时间:2012-08-31 21:56:58

标签: c++ while-loop try-catch flow-control

我有这个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 个答案:

答案 0 :(得分:6)

将break关键字添加到catch

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

答案 1 :(得分:2)

bool flag1 = true, flag2 = true;
while (flag1)
{
  // some work so that flag2 == true
  while (flag2)
  {
    try
    {

    }
    catch (...) // any exception happens
    {
        break;
    }
  }
}

答案 2 :(得分: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)

答案 3 :(得分: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 (...) {}
    }
}