Standard Exception Classes

Classes are provided in the Standard C++ Library to report program errors. These classes are declared in the <stdexcept> header. All of these classes inherit from a common base class named exception. The two classes logic_error and runtime_error inherit from exception and serve as base classes for more specific errors.

These classes provide a common framework for the way errors are handled in a C++ program. System-specific error handling can be provided by creating classes that inherit from these standard exception classes.

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.

152 Standardizing Your Code