# C++ Notes: Exceptions

## Exceptions and the `throw` and `try..catch` statements

Exceptions allow passing information about some exception condition (usually an error) by means of the `throw` statement to the `catch` clause that encloses it or any of the calls on the call stack. The beauty of this solution is that calls look identical, and the error processing code is in the function that wants to catch it.

## `throw` something

The `throw` statement can throw a value of any type, but if your exceptional condition fits into one of the standard exceptions, use it. As a rule, use one of the `logic_error` exceptions if the error is a result of a programming logic error, eg, the programmer should have checked the bounds before referencing an element in a container. Use one of the `runtime_errors` if the error is the result of input that the programmer can not easily check for, eg, input values that result in ranges being exceeded, too much data, etc.

## Standard exceptions

The C++ library defines a number of common exceptions. Use

    #include <stdexcept>
    using namespace std;  // Or prefix names with std::

to get the following classes defined. These are arranged in a class hierarchy shown by the indentation below.

- `exception`
  - `logic_error`
    - `domain_error`
    - `invalid_argument`
    - `length_error`
    - `out_of_range`
  - `runtime_error`
    - `range_error`
    - `overflow_error`
    - `underflow_error`

## Standard exception constructor

To create an exception and throw it, call the constructor with a c-string parameter.

    throw out_of_range("Subscript less than zero");

## Catching a standard exception

You can catch an exception of a specific type, or any of its subclasses, by specifying the class name as the type of the parameter in the `catch` clause. Call the `what` method to get the error string from a standard exception.

    vector<int> v;   // using standard vector class
    . . .
    try {
        . . .
        x = v.at(-2); // this throws out_of_range exception.
        . . .
    } catch (out_of_range e) {
        cerr << e.what() << endl;  // print error
        exit(1);  // stop program
    }

## Other pre-defined exceptions

Altho C++ popularized exceptions, they aren't used extensively within the STL or other libraries because exceptions were not available in all implementations for a long time. You can pursue these, but I don't think I'll write notes on them.

- Memory allocation errors.
- I/O errors.