What is the difference between std::runtime_error and std::exception? What is the appropriate use for each? Why are they different in the first place?
std::exception
is the class whose only purpose is to serve as the base class in the exception hierarchy. It has no other uses. In other words, conceptually it is an abstract class (even though it is not defined as abstract class in C++ meaning of the term).
std::runtime_error
is a more specialized class, descending from std::exception
, intended to be thrown in case of various runtime errors. It has a dual purpose. It can be thrown by itself, or it can serve as a base class to various even more specialized types of runtime error exceptions, such as std::range_error
, std::overflow_error
etc. You can define your own exception classes descending from std::runtime_error
, as well as you can define your own exception classes descending from std::exception
.
Just like std::runtime_error
, standard library contains std::logic_error
, also descending from std::exception
.
The point of having this hierarchy is to give user the opportunity to use the full power of C++ exception handling mechanism. Since 'catch' clause can catch polymorphic exceptions, the user can write 'catch' clauses that can catch exception types from a specific subtree of the exeption hierarchy. For example, catch (std::runtime_error& e)
will catch all exceptions from std::runtime_error
subtree, letting all others to pass through (and fly further up the call stack).
P.S. Designing a useful exception class hierarchy (that would let you catch only the exception types you are interested in at each point of your code) is a non-trivial task. What you see in standard C++ library is one possible approach, offered to you by the authors of the language. As you see, they decided to split all exception types into "runtime errors" and "logic errors" and let you proceeed from there with your own exception types. There are, of course, alternative ways to structure that hierarchy, which might be more appropriate in your design.
std::exception should be consider (note the considered) the abstract base of the standard exception hierarchy. This is because there is no mechanism to pass in a specific message (to do this you must derive and specialize what()). There is nothing to stop you using std::exception and for simple application it may be all you need.
std::runtime_error on the other hand has valid constructors that accept a string as a message. When what() is called a const char pointer is returned that points at a C string that has the same string as was passed into the constructor.
try
{
if (badThingHappened)
{ throw std::runtime_error("Something Bad happened here");
}
}
catch(std::exception const& e)
{
std::cout << "Exception: " << e.what() << "\n";
}