MistyD
MistyD

Reputation: 17223

Boost exception and thread safety - benefit over regular exception handling

I came across this article and it states (copy - pasted for convenience). I do not understand it and how its more beneficial then usual exception handling. In the do_work code the error instance is passed as a reference to a newly created thread. Now if there is an error it is rethrown. What is happening after that ? what do the following methods do ?

error = boost::exception_ptr();
error = boost::current_exception();

This is from the link

The other bonus of using boost exception is the thread safety capability. It allows for an exception to carry over between threads without issues.

For instance this function that throw an clone-ready exception:

void do_work()
{
    boost::exception_ptr error;
    boost::thread t( boost::bind(worker_thread,boost::ref(error)) );
    t.join();
    if( error )
        boost::rethrow_exception(error);
}

Could be intercepted and cloned to be carried by an other thread safely, for instance:

#include <boost/exception_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

void do_work(); //throws cloning-enabled boost::exceptions

void worker_thread( boost::exception_ptr & error )
{
    try
    {
        do_work();
        error = boost::exception_ptr();
    }
    catch(...)
    {
        error = boost::current_exception();
    }
}

Upvotes: 2

Views: 306

Answers (1)

Stephan Dollberg
Stephan Dollberg

Reputation: 34538

boost::exception_ptr() will default construct an exception pointer which is similar to a null pointer meaning that in the if-check it will evaluate to false indicating no error.
boost::current_exception() returns an exception pointer to the current active exception in a catch clause. It basically captures the exception so that you can rethrow it in the if check.

As an alternative to avoid all this boilerplate code I would recommend to use std::async/boost::async which offers all that out of the box.

I am not sure what you mean by "normal" exception handling but this allows you to handle errors on the call side indicating that your thread didn't finish the work it was supposed to do.

Upvotes: 4

Related Questions