Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 18

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 18 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 182018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

In fact, you have tocope with potential out-of-memory for every single operation that canallocate memory, because an out-of-memory condition can arise inany such operation.• When an out-of-memory situation arises that stops some operationfrom happening, you must not lose any data, but must roll back to anacceptable and consistent state.• When an out-of-memory situation occurs partway through an operation that involves the allocation of several resources, you must cleanup all those resources as part of the process of rolling back.For example, consider the case where you are keying data into anapplication for taking notes.

Each key you press potentially expands thebuffers used to store the information. If you press a key that requires thebuffers to expand, but there is insufficient memory available, the operationwill fail. In this case, it would clearly be quite wrong for the applicationto terminate – all your typing would be lost. Instead, the document mustroll back to the state it was in before the key was processed, and anymemory that was allocated successfully during the partially performedoperation must be freed.The Symbian OS error-handling and cleanup framework is good formore than out-of-memory errors. Many operations can fail becauseof other environment conditions, such as reading and writing to files,72OBJECTS – MEMORY MANAGEMENT, CLEANUP AND ERROR HANDLINGopening files, sending and receiving over communications sessions.

Theerror-handling and cleanup framework can help to deal with these kindsof error too.Even user input errors can be handled using the cleanup framework. Asan example, code that processes the OK button on a dialog can allocatemany resources before finding that an error has occurred. Dialog codecan use the cleanup framework to flag an error and free the resourceswith a single function call.PanicsThere’s just one kind of error that the cleanup framework can’t deal with:programming errors. If you write a program with an error, you have tofix it.

The best Symbian OS can do for you (and your users) is to killyour program as soon as the error is detected, with enough diagnostics togive you a chance to identify the error and fix it – hopefully, before yourelease the program. In Symbian OS, this is called a panic.The basic function to use here is User::Panic(). This takes astring that we call the panic category, and a 32-bit integer number.

Thecategory and the number, in combination, serve as a way of identifyingthe programming error. The panic category should be no longer than 16characters, but if it is longer, then only the first 16 characters are used.On real hardware, after terminating the originating process, a panicsimply displays a dialog titled ’Program closed’, citing the process name,the panic category and the number passed in the Panic() function call.A typical pattern is to code a global function (or a class static function,which is better) that behaves like this:static void Panic(TInt aPanic){LIT(KPanicCategory, "MY-APP");User::Panic(KPanicCategory, aPanic);}You can call this with different integer values.The reason for raising a panic, as we have said, is to deal with programming errors, and not environmental errors such as out-of-memory.A common use is for checking the parameters passed to a function call.For some parameters, there may be a defined range of valid values, andaccepting a value outside that range could cause your code to misbehave.You therefore check that the parameter is within range, and raise a panicif it’s not.

Another common use is where you want to ensure that afunction is called only if your program is currently in a particular state,and raise a panic if not.A commonly used way of raising panics is to use assert macros, ofwhich there are two, __ASSERT_DEBUG and __ASSERT_ALWAYS. TheERROR HANDLING73first is only compiled into debug versions of your program, while thelatter is compiled into both debug versions and production versions. Asa general rule, put as many as you can into your debug code, and asfew as you can into your release code. In other words, do your owndebugging – don’t let your users do it for you.The following code shows the use of the assert macro.enum TMyAppPAnic{...EMyAppIndexNegative = 12,...}void CMyClass::Foo(TInt aIndex){__ASSERT_ALWAYS(aIndex > 0, Panic(EMyAppIndexNegative));...}The pattern here is __ASSERT_ALWAYS(condition, expression), where the expression is evaluated if the condition isnot true.

CMyClass::Foo() should only be called with positive valuesof parameter aIndex, so we panic with code EMyAppIndexNegativeif not. This gets handled by the Panic() function presented previously,so that if this code were executed on a production machine, it wouldshow ‘Program closed’ with a category of MY-APP and a code of 12. Thenumber 12 comes from the enumeration TMyAppPanic containing a listof panic codes.Leave and the TRAP HarnessThe majority of errors suffered by a typical program are environmenterrors, typically caused by a lack of suitable resources at some criticaltime, the most common of which is lack of memory.

In such circumstancesit is usually impossible to proceed, and the program must roll back tosome earlier known state, cleaning up resources that are now no longerneeded.Leaving is part of that mechanism. A leave is invoked by calling thestatic function User::Leave() from within a trap harness. The trapharness catches errors – more precisely, it catches any functions thatleave. If you’re familiar with the exception handling in standard C++ orJava, TRAP() is like try and catch all in one, User::Leave() is likethrow, and a function with L at the end of its name is like a functionwith throws in its prototype.In a typical program, code can enter a long sequence of function callswhere one function calls another which, in turn, calls another.

If the74OBJECTS – MEMORY MANAGEMENT, CLEANUP AND ERROR HANDLINGinnermost function in this nested set of calls can’t, for example, allocatememory for some object that it needs to create, then you might expectthat function to return some error value back to its caller. The callingfunction has to check the returned value, and it in turn needs to return anerror value back to its caller. If each calling function needs to check forvarious return values, the code quickly becomes intractably complex.Use of the trap harness and leave can cut through all this.User::Leave() causes execution of the active function to terminate,and to return through all calling functions, until the first one is found thatcontains a TRAP() or TRAPD() macro.

Just as important, it rolls backthe stack frame as it goes.You can find the TRAP() and TRAPD() macros in e32std.h. It isnot important to understand their implementations; the main points areas follows.• TRAP() calls a function (its second parameter) and returns its leavecode in a 32-bit integer (its first parameter).

If the function returnsnormally, without leaving, then the leave code will be KErrNone(defined as zero).• TRAPD() defines the leave code variable first, saving you a line ofsource code, and then essentially calls TRAP().For example, in an application having word processing-type behavior,a key press might cause many things to happen, such as the allocation ofundo buffers and the expansion of a document to take the new characteror digit. If anything goes wrong, you might want to undo the operationcompletely, using code such as the following.TRAPD(error, HandleKeyL());if(error){RevertUndoBuffer();// Any other special cleanupUser::Leave(error);}If the HandleKeyL() function leaves, error contains the leavevalue, which is always negative.

If the function does not leave, errorcontains 0.On detecting a leave in HandleKeyL(), this code fragment performs some specialized cleanup, then calls User::Leave() itself. TheSymbian OS framework provides a TRAP statement outside the userapplication code, which catches the leave and posts the error message.While leaving can save a lot of hard coding effort, it does present aproblem. A typical program allocates objects on the heap, quite oftenERROR HANDLING75lots of them. It is also common behavior for a function to store a pointerto a heap object in an automatic variable, even if only temporarily.If, at the time a leave is taken, the automatic variable is the onlypointer to that heap object, then knowledge of this heap object willbe lost when a leave is taken, causing a memory leak.

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

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

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

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