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?
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 ).
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.
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 fromstd::exception
, using theenable_error_info
function with such user-defined types would introduce dangerous ambiguity which would break allcatch(std::exception &)
statements.Of course,
boost::exception
should not be used to replacestd::exception
as a base type in exception type hierarchies. Instead, it should be included as a virtual base, in addition tostd::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With