>
>
Processing of exceptions inside paralle…

Andrey Karpov
Articles: 643

Processing of exceptions inside parallel sections

Some time ago I wrote in the blog about some problems (see note "OpenMP and exceptions") occurring when an exception excesses the boundaries of parallel sections. I have also told you that an exception can be generated by new operator and that is must be caught and processed before it leaves the parallel section. The constructions used for this are rather inconvenient and complicated. Not so long ago I was told that in this case the smartest solution is using new operator which does not generate exceptions. That is using of a "nothrow"-variant of new operator which returns NULL in case of failure and allows you to write a simpler OpenMP code.

To get acquainted with new operator which does not generate exceptions see the article "Nothrow new". And here I will give only two examples which demonstrate the idea of the solution very clear.

The code with processing of an exception:

size_t errCount = 0;
#pragma omp parallel for num_threads(4) reduction(+: errCount)
for(int i = 0; i < 4; i++)
{
  try {
    float *ptr = new float[10000];
    // code
    delete [] ptr;
  }
  catch (std::bad_alloc &)
  {
    ++errCount;
  }
}

Simplified code without processing of exceptions:

size_t errCount = 0;
#pragma omp parallel for num_threads(4) reduction(+: errCount)
for(int i = 0; i < 4; i++)
{
  float *ptr = new(std::nothrow) float[10000];
  if (ptr == NULL) {
    ++errCount;
  } else {
    // code
    delete [] ptr;
  }
}