C++ Try Catch inside loop

18,961

add the break keyword to the catch

Also notice that you have b == false; That is checking that b is equal to false, not setting b = false.

Share:
18,961
perr0
Author by

perr0

Updated on July 30, 2022

Comments

  • perr0
    perr0 almost 2 years

    I have this C++ program with the following general structure

    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)
    

    I want it to get out of 2nd loop when there's an exception and go back to 1st loop until condition B is tue again. As described above it doesn't work as I expect. What seems to be happening is that code gets stuck in catch and never leaves it.

    How can I arrange it to make it work as I need?

    Note: condition A is never false.

  • ajon
    ajon over 11 years
    I think I will disagree here. I think it is totally fine to include ==true. It makes it more explicit and can at times be more readable. It is just a matter of coding conventions and styles. Personally, I do not include them, but I don't mind seeing them from other people.
  • perr0
    perr0 over 11 years
    Thank you! And indeed, I made a double mistake with condition == B inside catch (here and in the code itself). Thanks for pointing that out too. This show I need to read about break and continue again. I was trying continue but didn't even think about break (thought that it would stop program execution completely).
  • Grzegorz
    Grzegorz over 11 years
    No problem. I am not following my style, though, but what the coding gurus were teaching my at the university. I am passing this knowledge only.
  • ajon
    ajon over 11 years
    break will break out of the current for loop. Glad to help.