Q_A
Q_A

Reputation: 451

C++ - Continuing a while loop upon exception

When an exception is encountered in C++, does the program automatically terminate upon catching it. 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?

Upvotes: 0

Views: 106

Answers (2)

David Hammen
David Hammen

Reputation: 33126

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.

  • Make the advance member function return a value indicating whether the player's position was advanced. 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. The calling code will need to catch the exception.

There are lots of other ways to solve this problems.

Upvotes: 1

Emilian Cebuc
Emilian Cebuc

Reputation: 351

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

Upvotes: 0

Related Questions