8

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?

1
  • Without actually digging into the Boost code, I suspect that it has conditionals that defer to the std versions when run on an appropriate compiler, so they actually are in the same inheritance path. Nov 18, 2014 at 16:32

1 Answer 1

9

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.

2
  • How do you explain that boost::bad_lexical_cast can be caught by (boost::exception &) if the former is not derived from boost::exception?
    – James
    Nov 18, 2014 at 21:46
  • @James : because boost::throw_exception was used to throw the exception, which enriches the exception - among other things by dynamically adding boost::exception as a base (for more details, click the link). Nov 19, 2014 at 8:56

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.