16.13. Standard Library Exception Hierarchy
Experience has shown that exceptions fall nicely into a number of categories. The C++ Standard Library includes a hierarchy of exception classes (Fig. 16.11). As we first discussed in Section 16.3, this hierarchy is headed by base-class exception (defined in header file <exception>), which contains virtual function what, which derived classes can override to issue appropriate error messages.
Figure 16.11. Standard Library exception classes.
Placing a catch handler that catches a base-class object before a catch that catches an object of a class derived from that base class is a logic error. The base-class catch catches all objects of classes derived from that base class, so the derived-class catch will never execute.
Class logic_error is the base class of several standard exception classes that indicate errors in program logic. For example, class invalid_argument indicates that an invalid argument was passed to a function. (Proper coding can, of course, prevent invalid arguments from reaching a function.) Class length_error indicates that a length larger than the maximum size allowed for the object being manipulated was used for that object. Class out_of_range indicates that a value, such as a subscript into an array, exceeded its allowed range of values.
Class runtime_error, which we used briefly in Section 16.8, is the base class of several other standard exception classes that indicate execution-time errors. For example, class overflow_error describes an arithmetic overflow error (i.e., the result of an arithmetic operation is larger than the largest number that can be stored in the computer) and class underflow_error describes an arithmetic underflow error (i.e., the result of an arithmetic operation is smaller than the smallest number that can be stored in the computer).
Common Programming Error 16.9
Error-Prevention Tip 16.6
To catch all exceptions potentially thrown in a try block, use catch(...). One weakness with catching exceptions in this way is that the type of the caught exception is unknown at compile time. Another weakness is that, without a named parameter, there is no way to refer to the exception object inside the exception handler.
Software Engineering Observation 16.10
The standard exception hierarchy is a good starting point for creating exceptions. Programmers can build programs that can throw standard exceptions, throw exceptions derived from the standard exceptions or tHRow their own exceptions not derived from the standard exceptions.
Software Engineering Observation 16.11