title: Elegant exceptionhandling in OpenMP
body: <p>OpenMP forbids code which leaves the openmp block via exception. Therefore I'm looking for a nice way of getting the exceptions from an openmp block with the purpose of rethrowing it in the main thread and handling at a later point. So far the best I've been able to come up with is the following:</p>
  
  <pre><code>class ThreadException {
      std::exception_ptr Ptr;
      std::mutex         Lock;
  public:
      ThreadException(): Ptr(nullptr) {}
      ~ThreadException(){ this-&gt;Rethrow(); }  
      void Rethrow(){
          if(this-&gt;Ptr) std::rethrow_exception(this-&gt;Ptr);
      }
      void CaptureException() { 
          std::unique_lock&lt;std::mutex&gt; guard(this-&gt;Lock);
          this-&gt;Ptr = std::current_exception(); 
      }   
  };
  //...
  ThreadException except;
  #pragma omp parallel
  {
      try {
        //some possibly throwing code
      } 
      catch(...) { except.CaptureException(); }
  }
  </code></pre>
  
  <p>While this works nicely, rethrowing possible exceptions from the parallel section as soon as the <code>ThreadException</code> object is destroyed, this construct is still a bit unwieldy to use with putting a <code>try {}catch(...){}</code> around each section and having to manually capture the exception.</p>
  
  <p>So my question is: Does anyone know a more elegant (less verbose) way to do this (and if so, what does it look like)?</p>