All standard exception classes derive ultimately from the class exception, defined in the header
//: C01:StdExcept.cpp
// Derives an exception class from std::runtime_error
#include
#include
using namespace std;
class MyError : public runtime_error {
public:
MyError(const string& msg = "") : runtime_error(msg) {}
};
int main() {
try {
throw MyError("my message");
}
catch (MyError& x) {
cout << x.what() << endl;
}
} ///:~
Although the runtime_error constructor passes the message up to its std::exception subobject to hold, std::exception does not provide a constructor that takes a std::string argument. Therefore, you usually want to derive your exception classes from either runtime_error or logic_error (or one of their derivatives), and not from std::exception.
The following tables describe the standard exception classes.
exception | The base class for all the exceptions thrown by the C++ standard library. You can ask what( ) and retrieve the optional string with which the exception was initialized. |
logic_error | Derived from exception. Reports program logic errors, which could presumably be detected by inspection. |
runtime_error | Derived from exception. Reports runtime errors, which can presumably be detected only when the program executes. |
The iostream exception class ios::failure is also derived from exception, but it has no further subclasses.
You can use the classes in both of the following tables as they are, or you can use them as base classes from which to derive your own more specific types of exceptions.
Exception classes derived from logic_error | |
---|---|
domain_error | Reports violations of a precondition. |
invalid_argument | Indicates an invalid argument to the function from which it’s thrown. |
length_error | Indicates an attempt to produce an object whose length is greater than or equal to npos (the largest representable value of type size_t). |
Out_of_range | Reports an out-of-range argument. |
Bad_cast | Thrown for executing an invalid dynamic_cast expression in runtime type identification (see Chapter 8). |
bad_typeid | Reports a null pointer p in an expression typeid(*p). (Again, a runtime type identification feature in Chapter 8). |
Exception classes derived from runtime_error | |
---|---|
range_error | Reports violation of a postcondition. |
overflow_error | Reports an arithmetic overflow. |
bad_alloc | Reports a failure to allocate storage. |
Exception specifications