|
Boost Users : |
Subject: [Boost-users] [Exception] How do I inherit custom exception hierarchy from std::runtime_error rather than from std::exception?
From: Egor Tensin (egor.tensin_at_[hidden])
Date: 2013-11-27 11:19:00
Hi,
The issue that's confusing me arose from my intention of inheriting my
exception classes from std::runtime_error rather than from
std::exception. It seemed logical to me, as my exceptions are really
runtime errors; getting something meaningful via what() also seemed
like a good idea. However, this doesn't compile:
#include <iostream>
#include <stdexcept>
#include <boost/exception/all.hpp>
typedef boost::error_info<struct tag_foo_info, unsigned long> foo_info;
struct foo_error : virtual boost::exception, virtual std::runtime_error
{
explicit foo_error(const char *const what)
: std::runtime_error(what)
{ }
explicit foo_error(const std::string& what)
: std::runtime_error(what)
{ }
};
static void foo()
{
BOOST_THROW_EXCEPTION(foo_error("foo error") << foo_info(42));
}
int main(int argc, char *argv[])
{
try
{
foo();
}
catch (const std::exception& e)
{
std::cerr << boost::diagnostic_information(e);
return 1;
}
return 0;
}
It says that there's no default constructor available for
std::runtime_error. How do I fix this or should I use the idiomatic
approach? The interesting thing is that if I erase the "virtual"
keyword, the program compiles flawlessly. I wonder what is the reason
for that, e.g. why the original code doesn't work and why the new code
does, what are the consequences of making boost::exception and
std::runtime_error base (non-virtual) classes, etc. I'm confused as
the docs clearly recommends I build exception classes hierarchy using
virtual inheritance. Could somebody please give me an insight into the
inner workings of the library & inheritance mechanisms?
Thank you in advance,
Egor.
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net