Главная » Просмотр файлов » Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007

Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 22

Файл №779887 Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (Symbian Books) 22 страницаWiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887) страница 222018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Control returns to the callingfunction, which, if no trap harness exists, will also exit at that point. Thisprocess continues up the calling chain until a trap harness is encountered,at which time the error is handled. Figure 4.2 illustrates this exiting processup an example nested calling chain to a harness known, on Symbian OS,as a TRAP.As you can see, the leave is a more proactive way of indicating anerror. Unlike simple return codes, a leave cannot be ignored.When a function is interrupted and exited due to a leave (as Func2L(),Func3L(), and Func4L() are in Figure 4.2), it will act as if a returnoccurred at that point: the stack will unwind and all automatic variableswill go out of scope and thus will be deallocated from the stack. However,any cleanup that requires explicit destructor code will be skipped by the102SYMBIAN OS PROGRAMMING BASICSFunct0(){Func1()Func1(){TInt code;}TRAP(code,Func2())if (code){Func2L(){//handle trapFunc3L()Func3L(){}}}Func4L()Func4L(){Trap defined}User::Leave(code);Leave initiated}Figure 4.2 Leave/TRAPleave.

This is an issue that must be accounted for, and the correct way tohandle this is discussed in section 4.5.6.Since the leave and TRAP is similar to C++’s built-in try, throw,catch exception handling, you may wonder why Symbian invented itsown exception handling. The main reason is that exception handlingwas not a formal part of C++ at the time Symbian OS was written, andeven after it was introduced in C++, it was considered too inefficientfor Symbian OS. As a result, the compilers supplied with the SymbianOS SDK would flag an error if you tried to use the try, throw, orcatch mechanism in your code. However, with Symbian OS v9 this isno longer the case – standard exception handling is now allowed. In fact,in Symbian OS v9, leaves and TRAPs are built on top of standard C++exception handling.

However, Symbian recommends you only use thestandard exception handling if you are porting legacy code that alreadyuses it over to Symbian OS; otherwise, you should continue to use leavesand TRAPs. Also, you should not mix the two exception handling methodsin a single program. This chapter will cover the Symbian OS leaves andTRAPs only.EXCEPTION ERROR HANDLING AND CLEANUP103The following example code shows the use of a TRAP macro to invokea leaving function and trap any leave code that occurs. The functionUser::Leave() is used to execute a leave in the case of an error.void FooBarL(){TInt rc = SomeFunction();if (rc!=KErrNone){User::Leave(rc);// leave invoked}// The code here is not executed if a leave occurred above.}void MyFunctionL(){....FooBarL();// The code from here on will not be executed// if a leave occurred in FooBarL()...}void StartHere(){TInt leaveCode;// invoke MyFunctionL(), with a trap to catch leavesTRAP(leaveCode,MyFunctionL());if (leaveCode!=KErrNone){// MyFunctionL() left, handle leaveCode here}// Code always executs here - regardless of leaves in MyFunctionL()In the example, execution starts at StartHere().

StartHere()invokes MyFunctionL() through the TRAP macro and MyFunctionL() invokes FooBarL() (without a TRAP). If rc is an error inFooBarL() (due to a SomeFunction() failure), then the system staticAPI function User::Leave() is called. This will cause FooBarL()to stop executing at that point and return to MyFunctionL(). SinceMyFunctionL() did not define a trap handler when calling FooBarL() (i.e., the TRAP macro was not used), then MyFunctionL() willexit immediately after the call to FooBarL(), propagating the exceptionto its calling function, StartHere().Since we invoked MyFunctionL() using the TRAP macro inStartHere(), then StartHere() will not automatically exit.

Instead,the leave code is written to the first argument of the TRAP macro(leaveCode) and execution continues normally. If a leave did not occur,leaveCode is set to KErrNone (= 0).Execution always continues normally after the TRAP macro, whetheror not a leave event occurred. A simple if statement after the TRAPhandles leaveCode.1044.5.3SYMBIAN OS PROGRAMMING BASICSThe TRAP and TRAPD MacrosLet’s look at the TRAP macro in more detail. TRAP takes two arguments.The first is a TInt variable in which the leave code is placed. The secondis the function you want to invoke and trap the leave codes from.Here is an example TRAP call:TRAP(leaveCode, FunctionL())This statement invokes FunctionL() and if FunctionL() leaves(either directly or if a leave occurs further down the calling chain), thenleaveCode is set to the value with which the leave was seeded. If a leavedid not occur (the normal case) and FunctionL() executes to completion, leavecode is set to KErrNone (0). Note that the first argument canbe any variable name and that variable must have been declared previously (as a TInt) or the compiler will flag it as an undeclared variable.A variation on TRAP is TRAPD (the D is for declare).

TRAPD is thesame as TRAP except the TRAPD macro will declare the first argument(the leave code variable) so you do not have to. For example:TRAPD(leaveCode,MyFunctionL());is equivalent to:TInt leaveCode;TRAP(leaveCode,MyFunctionL());If TRAPD is used in place of TRAP (for example, in the StartHere()function shown in section 4.5.2), then the ‘TInt leaveCode;’ line wouldnot be needed. In fact, the compiler would generate a multiple declarationerror if you left that line in, since using the TRAPD in this case results inthe compiler seeing two TInt leaveCode declarations.

The same errorwould occur if you have multiple TRAPD calls using the same leave codevariable name in the first argument. To avoid multiple declaration errorsin that case, you could use TRAPD first and TRAP thereafter.What if you do not use TRAP or TRAPD in your code and a leaveoccurs? In this case, the operating system code will handle it dependingon the error. In many cases, the thread is killed.4.5.4 Leave FunctionsSymbian OS has a set of static API functions grouped in a class calledUser. This is where the leave functions reside.EXCEPTION ERROR HANDLING AND CLEANUP105Here are the different variations of the leave function:User::Leave(code);User::LeaveNoMemory();User::LeaveIfError(error);User::LeaveIfNull(TAny *aPtr);//////////simple leave, passing leave codeequivalent to User::Leave(KErrNoMemory)if error is negative, leave usingerror as the reason.if ptr is NULL, leave with KErrNoMemoryIn most cases, your experience will be in trapping (and handling leavecleanup issues) from system APIs that have the potential to leave.

If youlook at the SDK API reference, you will see the possible return codes forthe function and possible leave codes (if any). Functions that may leavehave a suffix of L (or LC), as discussed next.4.5.5 What Does the ‘L’ Suffix Mean?The Symbian OS convention is to add an L to the name of all functionsthat may leave. Why is this needed? The first reason is that it gives youa clue that you may want to trap some of the leave codes that couldoccur. The next reason (which is the most important) is that you need toknow that the function may actually exit at that point and not executethe lines further down.

You need to look at your code and think aboutthis carefully. Make sure the code will clean up any allocated resourcesproperly if a leave occurs.The following example shows some code with a cleanup problem – anaccident waiting to happen.MyFunction(){CThisObject *obj;obj = new CThisObject;...FuncL();...delete obj}If a leave occurs in FuncL(), the delete obj line would never becalled and you would be left with allocated memory on the heap.

Sinceobj is an automatic variable, it will go out of scope upon exit and you areleft with orphaned memory with no reference to it (a textbook exampleof a memory leak).To avoid this situation, you could structure your code such that deletesare never needed after functions that may leave, but this is an awkward,if not impossible, solution. Another option is to always use class membervariables instead of automatic variables when allocating heap memory,106SYMBIAN OS PROGRAMMING BASICSand perform the deletion in the class destructor.

But what else is left?Well, you can TRAP the function and have the TRAP handler call thedelete, and then just reissue the User::Leave() so that the real TRAPcan be handled further up in the call stack. Clever, but still awkwardto do for every call of an L function in your program, and expensive interms of runtime speed, because setting up a TRAP requires a call to thesystem. So what is the solution? Thankfully, Symbian provides a methodof handling this situation – the cleanup stack.4.5.6 Cleanup StackAutomatic pointer variables can be pushed onto a cleanup stack during afunction’s execution.

If a leave occurs in the function (either directly viathe User::Leave() function call, or from an L function that leaves),each pointer that was pushed on the cleanup stack is popped and freedbefore the function is exited. This will prevent the problem described inthe last section.Items that were pushed onto the cleanup stack must be manuallypopped off when there is no more danger of a leave occurring before thedeletion.

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

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

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

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