Читаем Thinking In C++. Volume 2: Practical Programming полностью

All standard exception classes derive ultimately from the class exception, defined in the header . The two main derived classes are logic_error and runtime_error, which are found in (which itself includes ). 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

#include

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.

exceptionThe 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_errorDerived from exception. Reports program logic errors, which could presumably be detected by inspection.
runtime_errorDerived 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_errorReports violations of a precondition.
invalid_argumentIndicates an invalid argument to the function from which it’s thrown.
length_errorIndicates 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_rangeReports an out-of-range argument.
Bad_castThrown for executing an invalid dynamic_cast expression in runtime type identification (see Chapter 8).
bad_typeidReports 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_errorReports violation of a postcondition.
overflow_errorReports an arithmetic overflow.
bad_allocReports a failure to allocate storage.

Exception specifications

Перейти на страницу:

Похожие книги

3ds Max 2008
3ds Max 2008

Одни уверены, что нет лучшего способа обучения 3ds Мах, чем прочитать хорошую книгу. Другие склоняются к тому, что эффективнее учиться у преподавателя, который показывает, что и как нужно делать. Данное издание объединяет оба подхода. Его цель – сделать освоение 3ds Мах 2008 максимально быстрым и результативным. Часто после изучения книги у читателя возникают вопросы, почему не получился тот или иной пример. Видеокурс – это гарантия, что такие вопросы не возникнут: ведь автор не только рассказывает, но и показывает, как нужно работать в 3ds Мах.В отличие от большинства интерактивных курсов, где работа в 3ds Мах иллюстрируется на кубиках-шариках, данный видеокурс полностью практический. Все приемы работы с инструментами 3ds Мах 2008 показаны на конкретных примерах, благодаря чему после просмотра курса читатель сможет самостоятельно выполнять даже сложные проекты.

Владимир Антонович Верстак , Владимир Верстак

Программирование, программы, базы данных / Программное обеспечение / Книги по IT