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
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.
That’s exactly why it’s titled “Abusing C++ exceptions”
Oh that’s right, I missed that fine point somehow…