using try catch to break an infinite loop

so i have a basic infinite loop here and i would like to know how to use a try/catch to exit the loop or prevent the loop from continuing..
(forgive me i saw this in some past exam question)

1
2
3
4
5
6
7
8
9
 
int main()
{
int x = 0;
while(x<10)
{
cout<<x<<endl;
}
Last edited on
Why?
That's arguably a misuse of exceptions, which are meant to handle exceptional circumstances that the programmer should not ignore. You can instead use break to jump out of the loop that it's in.

Still, try having a read through http://www.cplusplus.com/doc/tutorial/exceptions/ , then give it a try for yourself.

-Albatross
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

int main()
{
   int x = 0;

   try
   {
      while (x < 10)
      {
         std::cout << x << '\n';

         throw x;
      }
   }

   catch (...)
   {
      std::cout << "\nI'm done and outta here!\n";
   }
}
0

I'm done and outta here!


ETA: I forgot to mention doing this is like using a nuke to swat a gnat.

Exceptions are when exceptional things occur. This usage is not exceptional.
Last edited on
That's arguably a misuse of exceptions...


Yes.
But people do this stuff. And it survives and lingers on as a paradigm. The OP should at least see a few so he can recognize & understand them when found in the wild.

Also, there is the philosophy thing. shift is for shifting bits, but you see it frequently as a multiply by powers of 2, regardless of its intent and name. Misuse of tools will often net you a performance gain, simpler code, or some other 'lift' that would not be possible if you forced yourself to stick to 'how we guess (or rarely, how it was stated) that it was intended to be used'.

That said, misuse of exceptions is something I never really got a good explain on why one would do that. It is slower than doing things properly, in every test I ever did, and its cryptic and messy. It has no redeeming qualities -- its like a urban legend that won't die.

Misuse of tools will often net you a performance gain, simpler code, or some other 'lift' that would not be possible if you forced yourself to stick to 'how we guess (or rarely, how it was stated) that it was intended to be used'.

You're preaching to the choir here. I'm very much for this sort of "misuse" so long as it's reasonably documented and not done too soon.

But, as you said, exceptions as a form of flow control don't have many (if any) redeeming qualities. I have gripes with exceptions in C++ as-is, and I'd even hold up goto as a more elegant solution to this particular problem.

-Albatross
Topic archived. No new replies allowed.