Hbf
Hbf

Reputation: 3114

Boost rethrow_exception throws exception of different type

I am using Boost exception_ptr's and observe that rethrow_exception(ptr) does not give me the original exception. I've cooked it down to this:

struct error : virtual std::exception, virtual boost::exception {};

try { 
  boost::exception_ptr ptr(boost::copy_exception(error()));
  boost::rethrow_exception(ptr);
}
catch(boost::exception& e) {
  // e is a boost::exception_detail::clone_impl<error>
}

Shouldn't e be of type error instead of type clone_impl?

I am using Boost 1.49.0.

Upvotes: 4

Views: 1762

Answers (1)

Michael Simbirsky
Michael Simbirsky

Reputation: 3103

It is by design.

See http://www.boost.org/doc/libs/1_55_0/libs/exception/doc/frequently_asked_questions.html, section "Why is boost::exception abstract?"

The type of boost::exception is abstract to prevent user from "rethrowing" it. If user wants to rethrow, she is forced to use code like

catch( boost::exception & e )
{
    e << foo_info(foo);
    throw; //Okay, re-throwing the original exception object.
}

You can also look at this from a different perspective. The customer error type can be almost anything, it may not allow derivation from it or may be non-copyable or non-constructable at all (e.g. private constructors only accessible to friends). Therefore, Boost cannot assume anything about customer's type, cannot copy or derive/copy from it and can only keep a pointer to the existing object passed to boost::copy_exception.

Upvotes: 2

Related Questions