Главная » Просмотр файлов » Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356

Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 11

Файл №779879 Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (Symbian Books) 11 страницаIssott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879) страница 112018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Instead lower layers shoulddetect errors and pass them upwards to the layer that is capable ofcorrectly resolving them.Symbian OS provides direct support for escalating errors upwardsknown as the leave and trap operations. These allow errors to be propagated up the call stack by a leave and trapped by the layer that hassufficient context to resolve it. This mechanism is directly analogous toexception handling in C++ and Java.Symbian OS does not explicitly use the standard C++ exceptionhandling mechanism, for historical reasons. When Symbian OS, orEPOC32 as it was then known, was first established, the compilersavailable at that time had poor or non-existent support for exceptions.You can use C++ exceptions within code based on Symbian OS. However, there are a number of difficulties with mixing Leave and trapoperations with C++ exceptions and so it is not recommended that youuse C++ exceptions.StructureThe most basic structure for this pattern (see Figure 2.3) revolves aroundthe following two concepts:• The caller is the higher-layer component that makes a function callto another component.

This component is aware of the motivationfor the function call and hence how to resolve any system or domainerrors that might occur.17 Oneof the cardinal sins on Symbian OS.36ERROR-HANDLING STRATEGIESFigure 2.3Structure of Escalate Errors pattern• The callee is the lower-layer component on which the function callis made. This component is responsible for attempting to satisfy thefunction call if possible and detecting any system or domain errorsthat occur whilst doing so. If an error is detected then the functionescalates this to the caller through the Leave operation, otherwise thefunction returns as normal.An important point to remember when creating a function is that thereshould only be one path out of it. Either return an error or leave but donot do both as this forces the caller to separately handle all of the waysan error can be reported.

This results in more complex code in the callerand usually combines the disadvantages of both approaches!Note that all leaves must have a corresponding trap harness. This is toensure that errors are appropriately handled in all situations.18 A commonstrategy for resolving errors is to simply report the problem, in a top-leveltrap harness, to the end user with a simple message corresponding to theerror code.DynamicsNormally, a whole series of caller–callee pairs are chained together ina call stack. In such a situation, when a leave occurs, the call stack is18 If a Leave doesn’t have a trap associated with it, your thread will terminate with a USER175 panic since there’s little else Symbian OS can do.ESCALATE ERRORS37unwound until control is returned to the closest trap.

This allows an errorto be easily escalated upwards through more than one component sinceany component that doesn’t want to handle the error simply doesn’t trapit (see Figure 2.4).Layer 3::CallerLayer 2::Callee /CallerFunction()Layer 1::CalleeFunction()Leave(Error)Trap(Error)Resolve(Error)Since no Trap has beendefined in Layer 2 the callstack continues unwindingFigure 2.4 Dynamics of Escalate Errors patternThe most important decision to make is where you should place yourtrap harnesses. Having coarse-grained units of recovery has the advantageof fewer trap harnesses and their associated recovery code but with thedisadvantage that the recovery code may be general and complex.

Thereis also the danger that a small error leads to catastrophic results for the enduser. For instance, if not having enough memory to apply bold formattingin a word processor resulted in a leave that unwound the entire callstack, this might terminate the application without giving the end user theopportunity to save and hence they might lose their data! On the otherhand, too fine-grained units of recovery results in many trap harnessesand lots of recovery code with individual attention required to deal witheach error case as well as a potentially significant increase in the size ofyour executable.Unlike other operating systems, Symbian OS is largely event-driven sothe current call stack often just handles a tiny event, such as a keystrokeor a byte received.

Thus trying to handle every entry point with a separate38ERROR-HANDLING STRATEGIEStrap is impractical. Instead leaves are typically handled in one of threeplaces:• Many threads have a top-level trap which is used as a last resortto resolve errors to minimize unnecessary error handling in thecomponent. In particular, the Symbian OS application frameworkprovides such a top-level trap for applications. If a leave does occur inan application, the CEikAppUi::HandleError() virtual functionis called allowing applications to provide their own error-handlingimplementation.• Traps are placed in a RunL() implementation when using ActiveObjects (see page 133) to handle the result of an asynchronous servicecall. Or alternatively you can handle the error in the correspondingRunError() function if your RunL() leaves.• Trap harnesses can be nested so you do not need to rely on justhaving a top-level trap.

This allows independent sub-componentsto do their own error handling if necessary. You should considerinserting a trap at the boundary of a component or layer. Thiscan be useful if you wish to attempt to resolve any domain errorsspecific to your component or layer before they pass out of yourcontrol.ImplementationLeavesA leave is triggered by calling one of the User leave functions definedin e32std.h and exported by euser.dll. By calling one of thesefunctions you indicate to Symbian OS that you cannot finish the currentoperation you are performing or return normally because an error hasoccurred. In response, Symbian OS searches up through the call stacklooking for a trap harness to handle the leave.

Whilst doing so SymbianOS automatically cleans up objects pushed onto the cleanup stack bylower-level functions.The main leave function is User::Leave(TInt aErr) where thesingle integer parameter indicates the type of error and is equivalent toa throw statement in C++. By convention, negative integers are used torepresent errors.

There are a few helper functions that can be used inplace of User::Leave():• User::LeaveIfError(TInt aReason) leaves if the reason codeis negative or returns the reason if it is zero or positive.• User::LeaveIfNull(TAny* aPtr) leaves with KErrNoMemoryif aPtr is null.ESCALATE ERRORS39• new(ELeave) CObject() is an overload of the new operator thatautomatically leaves with KErrNoMemory if there is not enoughmemory to allocate the object on the heap.Here is an example where a function leaves if it couldn’t establisha connection to the file server due to some system error or because itcouldn’t find the expected file.

In each case, the higher layers are giventhe opportunity to resolve the error:void CEngine::ConstructL(const TDesC& aFileName){RFs fs;User::LeaveIfError(fs.Connect());RFile file;User::LeaveIfError(file.Open(fs,aFileName,EFileRead));...}By convention, the names of functions which can leave shouldalways be suffixed with an ‘L’ (e.g., ConstructL()) so that a calleris aware the function may not return normally. Such a function is frequently referred to as a leaving function. Note that this rule appliesto any function which calls a leaving function even if does not callUser::Leave() itself.

The function implicitly has the potential to leavebecause un-trapped leaves are propagated upward from any functionsit calls.Unfortunately you need to remember that this is only a conventionand is not enforced by the compiler so an ‘L’ function is not alwaysequivalent to a leaving function. However, static analysis tools such asepoc32\tools\leavescan.exe exist to help you with this. Thesetools parse your source code to evaluate your use of trap and leaveoperations and can tell you if you’re violating the convention. They alsocheck that all leaves have a trap associated with them to help you avoidUSER 175 panics.TrapsA trap harness is declared by using one of the TRAP macros definedin e32cmn.h.

These macros will catch any leave from any functioninvoked within a TRAP macro. The main trap macro is TRAP(ret,expression) where expression is a call to a leaving function19 andret is a pre-existing TInt variable. If a leave reaches the trap then theoperating system assigns the error code to ret; if the expression returnsnormally, without leaving or because the leave was trapped at a lower19 To be precise it doesn’t have to be a leaving function but then, if it isn’t, why wouldyou trap it?40ERROR-HANDLING STRATEGIESlevel in the call stack, then ret is set to KErrNone to indicate that noerror occurred.As the caller of a function within a trap you should not need toworry about resources allocated by the callee. This is because the leavingmechanism is integrated with the Symbian OS cleanup stack.

Any objectsallocated by the callee and pushed onto the cleanup stack are deletedprior to the operating system invoking the trap harness.In addition to the basic TRAP macro, Symbian OS defines the followingsimilar macros:• TRAPD(ret, expression) – the same as TRAP except that it automatically declares ret as a TInt variable on the stack for you (hencethe ‘D’ suffix) for convenience.• TRAP_IGNORE(expression) – simply traps expression andignores whether or not any errors occurred.Here is an example of using a trap macro:void CMyComponent::Draw(){TRAPD(err, iMyClass->AllocBufferL());if(err < KErrNone){DisplayErrorMsg(err);User::Exit(err);}... // Continue as normal}Intermediate TrapsIf a function traps a leave but then determines from the error code that it isunable to resolve that specific error, it needs to escalate the error furtherupwards.

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

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

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

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