The Boost Exception framework is great. You can add information to an exception derived from std::exception
and boost::exception
at the appropriate level of an application, as described in the documentation.
But how can such information be added if you do not control the throw site in the code, e.g. the std lib throws an exception, e.g. map throws out_of_range?
It cannot be caught as boost::exception, because it does not derive from it:
try {
my_map.at(id);
} catch(boost::exception &e) { // NOT caught
e << errinfo_desc("id not found, map out of range");
throw;
}
It can be caught as std::exception because out_of_range derives from std::exception, but then no information can be added because it not a boost::exception
:
try {
my_map.at(id);
} catch(std::exception &e) {
// compile error: e << errinfo_desc("id not found, map out of range");
throw;
}
Catching a std::exception
and throwing a new boost::exception
loses the original location of the exception which is not desired:
try {
my_map.at(id);
} catch(std::exception &e) {
BOOST_THROW_EXCEPTION(my_exception()
<< errinfo_desc("id not found, map out of range"));
}
Is is possible to preserve the original exception with its location etc. and still be able to add more information later? How?