Apache C++ Standard Library User's Guide

## 18.3 Using Exceptions

All exceptions thrown explicitly by any element of the Apache C++ Standard Library are guaranteed to be part of the library's exception hierarchy. Please review the Apache C++ Standard Library Reference Guide entries for these classes to determine which functions throw which exceptions. You can then choose to catch particular exceptions, or catch any that might be thrown by specifying the base class exception.

For instance, if you are going to call the `insert` function on string with a position value that could at some point be invalid, you should use code like this:

    string s;
    int n;
    ...
    try
    {
       s.insert(n,"Howdy");
    }
    catch (const std::exception& e)
    {
       // deal with the exception
    }

To throw your own exceptions, simply construct an exception of an appropriate type, assign it an appropriate message, and throw it. For example:

    ...
    if (n > max)
       throw std::out_of_range("You're past the end, bud");

The class exception serves as the base class for all other exception classes. As such it defines a standard interface. This interface includes the `what()` member function, which returns a null-terminated string that represents the message that was thrown with the exception. This function is likely to be most useful in a catch clause, as demonstrated in the example program in Section 18.4.

The class exception does not contain a constructor that takes a message string, although it can be thrown without a message. Calling `what()` on an exception object returns a default message. All classes derived from exception do provide a constructor that allows you to specify a particular message.

To throw a base exception, you could use the following code:

    throw std::exception;

This is generally not very useful, however, since whatever catches this exception has no idea what kind of error has occurred. Instead of a base exception, you will usually throw a derived class such as logic_error or one of its derivations, such as out_of_range in the example above. Better still, you can extend the hierarchy by deriving your own classes. This allows you to provide error reporting specific to your particular problem. For instance:

    class bad_packet_error : public std::runtime_error
    {
       public:
          bad_packet_error(const std::string& what);
    };

    if (bad_packet())
       throw bad_packet_error("Packet size incorrect");

This section has demonstrated how the C++ Standard Library exception classes provide you with a basic error model. From this foundation, you can build the right error detection and reporting methods required for your particular application.