Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming

Здесь есть возможность читать онлайн «Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2003, ISBN: 2003, Издательство: Prentice Hall, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Thinking In C++. Volume 2: Practical Programming: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Thinking In C++. Volume 2: Practical Programming»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Best selling author Bruce Eckel has joined forces with Chuck Allison to write
, the sequel to the highly received and best selling
. Eckel is the master of teaching professional programmers how to quickly learn cutting edge topics in C++ that are glossed over in other C++ books. In
, the authors cover the finer points of exception handling, defensive programming and string and stream processing that every C++ programmer needs to know. Special attention is given to generic programming where the authors reveal little known techniques for effectively using the Standard Template Library. In addition, Eckel and Allison demonstrate how to apply RTTI, design patterns and concurrent programming techniques to improve the quality of industrial strength C++ applications. This book is targeted at programmers of all levels of experience who want to master C++.

Thinking In C++. Volume 2: Practical Programming — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Thinking In C++. Volume 2: Practical Programming», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

//: C01:InitExcept.cpp

// Handles exceptions from subobjects

//{-bor}

#include

using namespace std;

class Base {

int i;

public:

class BaseExcept {};

Base(int i) : i(i) {

throw BaseExcept();

}

};

class Derived : public Base {

public:

class DerivedExcept {

const char* msg;

public:

DerivedExcept(const char* msg) : msg(msg) {}

const char* what() const {

return msg;

}

};

Derived(int j)

try

: Base(j) {

// Constructor body

cout << "This won't print\n";

}

catch (BaseExcept&) {

throw DerivedExcept("Base subobject threw");;

}

};

int main() {

try {

Derived d(3);

}

catch (Derived::DerivedExcept& d) {

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

}

} ///:~

Notice that the initializer list in the constructor for Derivedgoes after the trykeyword 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 catchclause .

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

//: C01:FunctionTryBlock.cpp

// Function-level try blocks

//{-bor}

#include

using namespace std;

int main() try {

throw "main";

} catch(const char* msg) {

cout << msg << endl;

return 1;

} ///:~

In this case, the catchblock can return in the same manner that the function body normally returns. Using this type of function-level tryblock isn’t much different from inserting a try-catcharound 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 . The two main derived classes are logic_errorand runtime_error, which are found in (which itself includes ). The class logic_errorrepresents 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_errorand logic_errorprovide a constructor that takes a std::stringargument 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_errorconstructor passes the message up to its std::exceptionsubobject to hold, std::exceptiondoes not provide a constructor that takes a std::stringargument. Therefore, you usually want to derive your exception classes from either runtime_erroror 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::failureis 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_castexpression in runtime type identification (see Chapter 8).
bad_typeid Reports a null pointer pin 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 throwstatements, 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 .

The exception specification reuses the keyword throw, followed by a parenthesized list of all the types of potential exceptions that the function can throw. Your function declaration might look like this: .

void f() throw(toobig, toosmall, divzero);

As far as exceptions are concerned, the traditional function declaration

void f();

means that any type of exception can be thrown from the function. If you say

void f() throw();

no exceptions whatsoever will be thrown from the function (so you’d better be sure that no functions farther down in the call chain let any exceptions propagate up!).

For good coding policy, good documentation, and ease-of-use for the function caller, always consider using exception specifications when you write functions that throw exceptions. (Exceptions to this guideline are discussed later in this chapter.)

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Thinking In C++. Volume 2: Practical Programming»

Представляем Вашему вниманию похожие книги на «Thinking In C++. Volume 2: Practical Programming» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Thinking In C++. Volume 2: Practical Programming»

Обсуждение, отзывы о книге «Thinking In C++. Volume 2: Practical Programming» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x