HP aC++/HP C Programmer's Guide (B3901-90036; A.06.26; September 2011)
Example
# include <stdexcept>
# include <iostream>
# include <string>
void f()
{
// details omitted
throw range_error(string(“some info”));
}
int main()
{
try {
f();
}
catch (runtime_error& r) {
// handle any kind of runtime error including range_error
cout << r.what() << ‘\n’;
}
}
The class logic_error defines objects thrown as exceptions to report errors due to
the internal logic of the program. The errors are presumably preventable and detectable
before execution. Examples are violations of logical preconditions or class invariants.
The subclasses of logic_error are:
• domain_error (the operation requested is inconsistent with the state of the object
it is applied to)
• invalid_argument
• length_error (an attempt to create an object whose size equals or exceeds
allowed size)
• out_of_range (an argument value not in the expected range)
Runtime errors are due to events out of the scope of the program. They cannot be predicted
before they happen. The subclasses of runtime_error are:
• range_error
• overflow_error (arithmetic overflow)
The exception class includes a void constructor, a copy constructor, an assignment
operator, a virtual destructor, and a function what that returns an implementation-defined
character string. None of these functions throw any exceptions.
Each of the subclasses includes a constructor taking an instance of the Standard C++
Library string class as an argument. They initialize an instance such that the function
what, when applied to the instance, returns a value equal to the argument to the
constructor.
Standard Exception Classes 189