简体   繁体   English

C ++-在出现异常时继续while循环

[英]C++ - Continuing a while loop upon exception

When an exception is encountered in C++, does the program automatically terminate upon catching it. 在C ++中遇到异常时,程序在捕获到异常时会自动终止。 Is there a way that ,if the exception was caught within a loop, I could just skip the rest of the loop and go straight to the next iteration? 有没有一种方法,如果在循环中捕获到异常,我可以跳过循环的其余部分,直接进入下一个迭代?

There are a number of different ways to solve this problem. 有多种解决此问题的方法。

  • Create a member function that checks whether a move is valid before making it. 创建一个成员函数,该函数在进行移动之前检查移动是否有效。 The calling code will need to call this function before calling advance , and only call advance if the move is valid. 调用代码将需要在调用advance之前调用此函数,并且仅在移动有效的情况下才调用advance

  • Make the advance member function return a value indicating whether the player's position was advanced. 使advance成员函数返回一个值,该值指示玩家的位置是否已提前。 The calling code will need to test the return value to decide whether to print the board or print a "try again" type of message. 调用代码将需要测试返回值,以决定是打印板还是打印“重试”类型的消息。

  • Make the advance member function throw an exception if the move is invalid. 如果移动无效,则使advance成员函数引发异常。 The calling code will need to catch the exception. 调用代码将需要捕获异常。

There are lots of other ways to solve this problems. 还有许多其他方法可以解决此问题。

Well first of all, if that snipped of code is EXACTLY how you copy-pasted it, it has some syntax errors. 好吧,首先,如果那段代码完全是您复制粘贴的方式,那么它就有一些语法错误。 This is how it should be written: 它应该这样写:

     int main() {
     ...
     Person *p = new Person("Neo");
     ...
     string in;
     while(cin >> in) {
      if (in == "q") {
       break;
      }
      else if (in == /*One of the eight directions North ... Northwest*/) {
       p->advance(in);
      } //this bracket here ends the if. after the parentheses, nothing else will execute
      else {
       cerr << "Input one of the eight directions" < endl;
      }
     }
    }

So yeah, if I understood correctly your problem, adding that closing bracket there should solve it. 是的,如果我正确理解了您的问题,请在此处添加右括号即可解决。 I hope this is what you needed and that it was helpful 我希望这是您所需要的,并且对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM