Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relationship between boost::exception and std::exception

Suppose there is the following code:

try {
      // Do some boost stuff here
}
catch (const std::exception & stdEx) {
     cout << stdEx.what() << endl;
}

Questions:

1) I know that code works for some boost exceptions, even though std::exception and boost::exception are not on the same inheritance path. Why does it work then?

2) Does it work that way for all boost exceptions? In other words, are there examples when a boost::exception handler that is below std::exception handler can be triggered?

like image 279
James Avatar asked Nov 18 '14 16:11

James


People also ask

Is boost exception derived from STD exception?

The recommendation is to have specific boost exception classes derive (virtually) from both boost::exception and std::exception , and not just from boost::exception . Some boost libraries' exceptions derive only from std::exception (like boost::bad_lexical_cast ), some from both (like boost::xpressive::regex_error ).

How do you throw a boost exception?

boost::throw_exception(x); is a replacement for throw x; that both degrades gracefully when exception handling support is not available, and integrates the thrown exception into facilities provided by Boost.


1 Answers

As you said, boost::exception does not derive from std::exception. For the reason, check the corresponding FAQ :

Despite that virtual inheritance should be used in deriving from base exception types, quite often exception types (including the ones defined in the standard library) don't derive from std::exception virtually.

If boost::exception derives from std::exception, using the enable_error_info function with such user-defined types would introduce dangerous ambiguity which would break all catch(std::exception &) statements.

Of course, boost::exception should not be used to replace std::exception as a base type in exception type hierarchies. Instead, it should be included as a virtual base, in addition to std::exception (which should probably also be derived virtually.)

The recommendation is to have specific boost exception classes derive (virtually) from both boost::exception and std::exception, and not just from boost::exception.

Some boost libraries' exceptions derive only from std::exception (like boost::bad_lexical_cast), some from both (like boost::xpressive::regex_error). I don't know of one that derives only from boost::exception though, so I'd say catching just std::exception should catch all.

like image 165
Sander De Dycker Avatar answered Sep 25 '22 18:09

Sander De Dycker