Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 78

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 78 страницаB. Stroustrup - The C++ Programming Language (794319) страница 782019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 78)

Asynchronous events requiremechanisms fundamentally different from exceptions (as defined here) to handle them cleanly andefficiently. Many systems offer mechanisms, such as signals, to deal with asynchrony, but becausethese tend to be system-dependent, they are not described here.13.1.4.2 Exceptions That Are Not ErrorsThink of an exception as meaning ‘‘some part of the system couldn’t do what it was asked to do’’(§13.1.1, §13.2).Exception throws should be infrequent compared to function calls or the structure of the systemhas been obscured.

However, we should expect most large programs to throw and catch at leastsome exceptions in the course of a normal and successful run.If an exception is expected and caught so that it has no bad effects on the behavior of the program, then how can it be an error? Only because the programmer thinks of it as an error and of theexception-handling mechanisms as tools for handling errors. Alternatively, one might think of theexception-handling mechanisms as simply another control structure, an alternative way of returninga value to a caller.

Consider a binary tree search function:void fnd(Tree∗ p, const string& s){if (s == p−>str) throw p;if (p−>left) fnd(p−>left,s);if (p−>right) fnd(p−>right,s);}// found sTree∗ find(Tree∗ p, const string& s){try {fnd(p,s);}catch (Tree∗ q) {// q->str==sreturn q;}return 0;}This actually has some charm, but it should be avoided because it is likely to cause confusion andinefficiencies. When at all possible, stick to the ‘‘exception handling is error handling’’ view.When this is done, code is clearly separated into two categories: ordinary code and error-handlingcode. This makes code more comprehensible.

Furthermore, the implementations of the exceptionmechanisms are optimized based on the assumption that this simple model underlies the use ofexceptions.Error handling is inherently difficult. Anything that helps preserve a clear model of what is anerror and how it is handled should be treasured.Section 13.1.5When You Can’t Use Exceptions34913.1.5 When You Can’t Use ExceptionsUse of exceptions is the only fully general and systematic way of dealing with errors in a C++ program. However, we must reluctantly conclude that there are programs that for practical and historical reasons cannot use exceptions. For example:• A time-critical component of an embedded system where an operation must be guaranteedto complete in a specific maximum time.

In the absence of tools that can accurately estimate the maximum time for an exception to propagate from a throw to a catch, alternativeerror-handling methods must be used.• A large old program in which resource management is an ad hoc mess (e.g., free store isunsystematically ‘‘managed’’ using ‘‘naked’’ pointers, news, and deletes), rather than relyingon some systematic scheme, such as resource handles (e.g., string and vector; §4.2, §4.4).In such cases, we are thrown back onto ‘‘traditional’’ (pre-exception) techniques. Because suchprograms arise in a great variety of historical contexts and in response to a variety of constraints, Icannot give a general recommendation for how to handle them.

However, I can point to two popular techniques:• To mimic RAII, give every class with a constructor an invalid() operation that returns someerror_code. A useful convention is for error_code==0 to represent success. If the constructorfails to establish the class invariant, it ensures that no resource is leaked and invalid() returnsa nonzero error_code. This solves the problem of how to get an error condition out of a constructor.

A user can then systematically test invalid() after each construction of an object andengage in suitable error handling in case of failure. For example:void f(int n){my_vector<int> x(n);if (x.invalid()) {// ... deal with error ...}// ...}•To mimic a function either returning a value or throwing an exception, a function can returna pair<Value,Error_code> (§5.4.3). A user can then systematically test the error_code aftereach function call and engage in suitable error handling in case of failure. For example:void g(int n){auto v = make_vector(n); // return a pairif (v.second) {// ...

deal with error ...}auto val = v.first;// ...}Variations of this scheme have been reasonably successful, but they are clumsy compared to usingexceptions in a systematic manner.350Exception HandlingChapter 1313.1.6 Hierarchical Error HandlingThe purpose of the exception-handling mechanisms is to provide a means for one part of a programto inform another part that a requested task could not be performed (that an ‘‘exceptional circumstance’’ has been detected). The assumption is that the two parts of the program are written independently and that the part of the program that handles the exception often can do something sensible about the error.To use handlers effectively in a program, we need an overall strategy. That is, the various partsof the program must agree on how exceptions are used and where errors are dealt with.

The exception-handling mechanisms are inherently nonlocal, so adherence to an overall strategy is essential.This implies that the error-handling strategy is best considered in the earliest phases of a design. Italso implies that the strategy must be simple (relative to the complexity of the total program) andexplicit. Something complicated would not be consistently adhered to in an area as inherentlytricky as error recovery.Successful fault-tolerant systems are multilevel. Each level copes with as many errors as it canwithout getting too contorted and leaves the rest to higher levels. Exceptions support that view.Furthermore, terminate() supports this view by providing an escape if the exception-handling mechanism itself is corrupted or if it has been incompletely used, thus leaving exceptions uncaught.Similarly, noexcept provides a simple escape for errors where trying to recover seems infeasible.Not every function should be a firewall.

That is, not every function can test its preconditionswell enough to ensure that no errors could possibly stop it from meeting its postcondition. The reasons that this will not work vary from program to program and from programmer to programmer.However, for larger programs:[1] The amount of work needed to ensure this notion of ‘‘reliability’’ is too great to be doneconsistently.[2] The overhead in time and space is too great for the system to run acceptably (there will bea tendency to check for the same errors, such as invalid arguments, over and over again).[3] Functions written in other languages won’t obey the rules.[4] This purely local notion of ‘‘reliability’’ leads to complexities that actually become a burden to overall system reliability.However, separating the program into distinct subsystems that either complete successfully or failin well-defined ways is essential, feasible, and economical.

Thus, major libraries, subsystems, andkey interface functions should be designed in this way. Furthermore, in most systems, it is feasibleto design every function to ensure that it always either completes successfully or fails in a welldefined manner.Usually, we don’t have the luxury of designing all of the code of a system from scratch.

Therefore, to impose a general error-handling strategy on all parts of a program, we must take intoaccount program fragments implemented using strategies different from ours. To do this we mustaddress a variety of concerns relating to the way a program fragment manages resources and thestate in which it leaves the system after an error. The aim is to have the program fragment appearto follow the general error-handling strategy even if it internally follows a different strategy.Occasionally, it is necessary to convert from one style of error reporting to another.

For example, we might check errno and possibly throw an exception after a call to a C library or, conversely,catch an exception and set errno before returning to a C program from a C++ library:Section 13.1.6Hierarchical Error Handling351void callC()// Call a C function from C++; convert errno to a throw{errno = 0;c_function();if (errno) {// ... local cleanup, if possible and necessary ...throw C_blewit(errno);}}extern "C" void call_from_C() noexcept// Call a C++ function from C; convert a throw to errno{try {c_plus_plus_function();}catch (...) {// ... local cleanup, if possible and necessary ...errno = E_CPLPLFCTBLEWIT;}}In such cases, it is important to be systematic enough to ensure that the conversion of error-reporting styles is complete. Unfortunately, such conversions are often most desirable in ‘‘messy code’’without a clear error-handling strategy and therefore difficult to be systematic about.Error handling should be – as far as possible – hierarchical.

If a function detects a run-timeerror, it should not ask its caller for help with recovery or resource acquisition. Such requests setup cycles in the system dependencies. That in turn makes the program hard to understand andintroduces the possibility of infinite loops in the error-handling and recovery code.13.1.7 Exceptions and EfficiencyIn principle, exception handling can be implemented so that there is no run-time overhead when noexception is thrown. In addition, this can be done so that throwing an exception isn’t all that expensive compared to calling a function.

Doing so without adding significant memory overhead whilemaintaining compatibility with C calling sequences, debugger conventions, etc., is possible, buthard. However, please remember that the alternatives to exceptions are not free either. It is notunusual to find traditional systems in which half of the code is devoted to error handling.Consider a simple function f() that appears to have nothing to do with exception handling:void f(){string buf;cin>>buf;// ...g(1);h(buf);}352Exception HandlingChapter 13However, g() or h() may throw an exception, so f() must contain code ensuring that buf is destroyedcorrectly in case of an exception.Had g() not thrown an exception, it would have had to report its error some other way. Consequently, the comparable code using ordinary code to handle errors instead of exceptions isn’t theplain code above, but something like:bool g(int);bool h(const char∗);char∗ read_long_string();bool f(){char∗ s = read_long_string();// ...if (g(1)) {if (h(s)) {free(s);return true;}else {free(s);return false;}}else {free(s);return false;}}Using a local buffer for s would simplify the code by eliminating the calls to free(), but then we’dhave range-checking code instead.

Complexity tends to move around rather than just disappear.People don’t usually handle errors this systematically, though, and it is not always critical to doso. However, when careful and systematic handling of errors is necessary, such housekeeping isbest left to a computer, that is, to the exception-handling mechanisms.The noexcept specifier (§13.5.1.1) can be most helpful in improving generated code.

Характеристики

Тип файла
PDF-файл
Размер
18,76 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6417
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее