I\'ve seen at least one reliable source (a C++ class I took) recommend that application-specific exception classes in C++ should inherit from std::exception
. I\
Reason for inheriting from std::exception
is it "standard" base class for exceptions, so it is natural for other people on a team, for example, to expect that and catch base std::exception
.
If you are looking for convenience, you can inherit from std::runtime_error
that provides std::string
constructor.
The main benefit is that code using your classes doesn't have to know exact type of what you throw
at it, but can just catch
the std::exception
.
Edit: as Martin and others noted, you actually want to derive from one of the sub-classes of std::exception
declared in <stdexcept>
header.
Difference: std::runtime_error vs std::exception()
Whether you should inherit from it or not is up to you. Standard std::exception
and its standard descendants propose one possible exception hierarchy structure (division into logic_error
subhierarchy and runtime_error
subhierarchy) and one possible exception object interface. If you like it - use it. If for some reason you need something different - define your own exception framework.
The problem with std::exception
is that there is no constructor (in the standard compliant versions) that accepts a message.
As a result I prefer to derive from std::runtime_error
. This is derived from std::exception
but its constructors allow you to pass a C-String or a std::string
to the constructor that will be returned (as a char const*
) when what()
is called.
You should inherit from boost::exception. It provides a lot more features and well-understood ways to carry additional data... of course, if you're not using Boost, then ignore this suggestion.
If all your possible exceptions derive from std::exception
, your catch block can simply catch(std::exception & e)
and be assured of capturing everything.
Once you've captured the exception, you can use that what
method to get more information. C++ doesn't support duck-typing, so another class with a what
method would require a different catch and different code to use it.