[Boost-users] Throwing an exception in a packaged_task: is there a clear example?

387 views
Skip to first unread message

Mark Wilson

unread,
Aug 19, 2010, 11:54:22 AM8/19/10
to boost...@lists.boost.org
Hello,

I am throwing an exception from a packaged_task, and then trying to catch it with f.get() (where f is a unique_future); it doesn't work, the program just terminates with:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::unknown_exception>'
  what():  std::exception


Is there a simple example somewhere, or could someone provide one, that makes clear how this mechanism is supposed to work?  The Threads documentation does not show how to do this...

Here is my simple program, based on the example in the docs:

#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
#include <boost/exception/all.hpp>

struct MyException
{
    MyException()
    {
    }
};

int calculate_the_answer_to_life_the_universe_and_everything()
{
    throw MyException();
    return 42;
}

int main()
{
    boost::packaged_task<int>
        task(calculate_the_answer_to_life_the_universe_and_everything);
    boost::unique_future<int> f(task.get_future());

    boost::thread t(boost::move(task));

    try
    {
        f.get();
    }
    catch(MyException& ex)
    {
        std::cout << "EXCEPTION!" << std::endl;
    }
}

Thanks,
Mark Wilson

Emil Dotchevski

unread,
Aug 19, 2010, 2:25:32 PM8/19/10
to boost...@lists.boost.org
On Thu, Aug 19, 2010 at 8:54 AM, Mark Wilson <mw...@lle.rochester.edu> wrote:
> Hello,
>
> I am throwing an exception from a packaged_task, and then trying to catch it
> with f.get() (where f is a unique_future); it doesn't work, the program just
> terminates with:
>
> terminate called after throwing an instance of
> 'boost::exception_detail::clone_impl<boost::unknown_exception>'
>   what():  std::exception
>
>
> Is there a simple example somewhere, or could someone provide one, that
> makes clear how this mechanism is supposed to work?  The Threads
> documentation does not show how to do this...

Try replacing throw MyException with
BOOST_THROW_EXCEPTION(MyException()). You'll need to #include
<boost/throw_exception.hpp>.

The page at http://beta.boost.org/doc/libs/release/libs/exception/doc/current_exception.html
explains why you get a boost::unknown_exception.

HTH,
Emil Dotchevski
Reverge Studios, Inc.
http://www.revergestudios.com/reblog/index.php?n=ReCode
_______________________________________________
Boost-users mailing list
Boost...@lists.boost.org
http://lists.boost.org/mailman/listinfo.cgi/boost-users

Mark Wilson

unread,
Aug 19, 2010, 3:25:27 PM8/19/10
to boost...@lists.boost.org
Thank you, Emil.   That works.
Reply all
Reply to author
Forward
0 new messages