Выбрать главу

    Derived d(3);

  }

  catch (Derived::DerivedExcept& d) {

    cout << d.what() << endl;  // "Base subobject threw"

  }

} ///:~

Notice that the initializer list in the constructor for Derived goes after the try keyword but before the constructor body. If an exception does indeed occur, the contained object is not constructed, so it makes no sense to return to the code that created it. For this reason, the only sensible thing to do is to throw an exception in the function-level catch clause.

Although it is not terribly useful, C++ also allows function-level try blocks for any function, as the following example illustrates:

//: C01:FunctionTryBlock.cpp

// Function-level try blocks

//{-bor}

#include <iostream>

using namespace std;

int main() try {

  throw "main";

} catch(const char* msg) {

cout << msg << endl;

return 1;

} ///:~

In this case, the catch block can return in the same manner that the function body normally returns. Using this type of function-level try block isn’t much different from inserting a try-catch around the code inside of the function body.

Standard exceptions

The set of exceptions used with the Standard C++ library is also available for your use. Generally it’s easier and faster to start with a standard exception class than to try to define your own. If the standard class doesn’t do exactly what you need, you can derive from it.

All standard exception classes derive ultimately from the class exception, defined in the header <exception>. The two main derived classes are logic_error and runtime_error, which are found in <stdexcept> (which itself includes <exception>). The class logic_error represents errors in programming logic, such as passing an invalid argument. Runtime errors are those that occur as the result of unforeseen forces such as hardware failure or memory exhaustion. Both runtime_error and logic_error provide a constructor that takes a std::string argument so that you can store a message in the exception object and extract it later with exception::what( ) , as the following program illustrates.

//: C01:StdExcept.cpp

// Derives an exception class from std::runtime_error

#include <stdexcept>

#include <iostream>

using namespace std;

class MyError : public runtime_error {

public:

  MyError(const string& msg = "") : runtime_error(msg) {}

};

int main() {

  try {

    throw MyError("my message");

  }

  catch (MyError& x) {

    cout << x.what() << endl;

  }

} ///:~

Although the runtime_error constructor passes the message up to its std::exception subobject to hold, std::exception does not provide a constructor that takes a std::string argument. Therefore, you usually want to derive your exception classes from either runtime_error or logic_error (or one of their derivatives), and not from std::exception.

The following tables describe the standard exception classes.

exception The base class for all the exceptions thrown by the C++ standard library. You can ask what( ) and retrieve the optional string with which the exception was initialized.
logic_error Derived from exception. Reports program logic errors, which could presumably be detected by inspection.
runtime_error Derived from exception. Reports runtime errors, which can presumably be detected only when the program executes.

The iostream exception class ios::failure is also derived from exception, but it has no further subclasses.

You can use the classes in both of the following tables as they are, or you can use them as base classes from which to derive your own more specific types of exceptions.

Exception classes derived from logic_error
domain_error Reports violations of a precondition.
invalid_argument Indicates an invalid argument to the function from which it’s thrown.
length_error Indicates an attempt to produce an object whose length is greater than or equal to npos (the largest representable value of type size_t).
Out_of_range Reports an out-of-range argument.
Bad_cast Thrown for executing an invalid dynamic_cast expression in runtime type identification (see Chapter 8).
bad_typeid Reports a null pointer p in an expression typeid(*p). (Again, a runtime type identification feature in Chapter 8).
Exception classes derived from runtime_error
range_error Reports violation of a postcondition.
overflow_error Reports an arithmetic overflow.
bad_alloc Reports a failure to allocate storage.

Exception specifications

You’re not required to inform the people using your function what exceptions you might throw. Failure to do so can be considered uncivilized, however, because it means that users cannot be sure what code to write to catch all potential exceptions. Of course, if they have your source code, they can hunt through and look for throw statements, but often a library doesn’t come with sources. Good documentation can help alleviate this problem, but how many software projects are well documented? C++ provides syntax that allows you to tell the user what exceptions this function throws, so the user can handle them. This is the optional exception specification, which adorns a function’s declaration, appearing after the argument list.