Symbian Developer Library

SYMBIAN OS V6.1 EDITION FOR C++

[Index] [Glossary] [Previous] [Next]



Using TRAP


Return Values

It is instructive to compare TRAP used with functions that do and do not return a value.

The code fragment below shows how to use TRAP for functions that don’t return a value. Note the L on the name of the function which indicates that it can leave:

TInt leaveValue;
TRAP(leaveValue, SomeFunctionL(arg1,arg2));
if (leaveValue)
 {
 // The function left; clean up fully-constructed objects
 }
else
 {
 // all is well
 }

The code fragment below shows a trap harness for a function that returns a value. That value is valid only if the function did not leave:

TInt leaveValue;
TInt functionValue;
TRAP(leaveValue, functionValue=SomeOtherFunctionL(arg1,arg2));
if (leaveValue)
 {
 // The function left; clean up fully-constructed objects
 // functionValue has no defined value
 }
else
 {
 // all is well; functionValue is valid
 }


Efficiency

The use of multiple C++ statements within a single TRAP can be more efficient than a nested sequence of TRAP statements. For example, it is possible to write:

TInt leaveValue;
...
TRAP(leaveValue,Action1L());
if (leaveValue ==KErrNone)
 {
 TRAP(leaveValue,Action2L());
 }
if (leaveValue!=KErrNone)
 {
 // handle the error
 ...
 }

However, it is more efficient and clearer to write:

TInt leaveValue;
...
TRAP(leaveValue,Action1L();Action2L());
if (leaveValue!=KErrNone)
 {
 // handle the error
 ...
 }