我有具有以下一般结构的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绝不为假。
将break关键字添加到捕获中
还要注意,您的b == false;那就是在检查b是否等于false,而不是设置b = false。
bool flag1 = true, flag2 = true;
while (flag1)
{
// some work so that flag2 == true
while (flag2)
{
try
{
}
catch (...) // any exception happens
{
break;
}
}
}
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)
。
您可以在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 (...) {}
}
}