Abusing C++ exceptions

Java and C# programmers use exceptions all over the place in their programs. C++ programmers have always been rather shy when it comes to exceptions. I’m not a particularly big fan of exceptions, but I find them helpful in getting me out of recursion trees!

The following snippet shows a typical recursive function that aims to find a target value by brute force. I’ve left out the details in order to highlight the most important feature : breaking out of the recursion tree once the value is found.

void go(int i)
{
   if(i == n)
   {
      // Perform calculation
     
      if (resultFound)
      {
         // This breaks out of the entire recursion 
         // tree and goes back to main!
         throw 1;
      }
   }
   else
   {
      state[i] = value1;
      go(i+1);
      state[i] = value2;
      go(i+1);
   }
}

int main()
{
   try {
      go(0);
   } catch(...) {}

   return 0;
}

Advertisement

3 Responses to Abusing C++ exceptions

  1. Kommie P. says:

    It’s a nice hack but wouldn’t it be a misuse of exceptions? And besides, I understand exceptions are expensive to throw and catch. And what if you forget to catch it whent it’s thrown? I wonder what purists would say.

  2. Kommie P. says:

    Oh that’s right, I missed that fine point somehow… :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.