Chapter 10: Error Handling
97
TI
-
89 / TI
-
92 Plus Developer Guide
Not for Distribution
Beta Version January 26, 2001
10.4. Catching Errors
Sometimes, you would like your application to catch error conditions rather than
allowing the system error handler to display an error message. The TRY,
ONERR, and ENDTRY macros are used together to give your app control over
error conditions.
TRY
/* code which can throw an error */
ONERR
/* execution continues here only if an error was thrown above */
ENDTRY
Begin a block of code which can throw an error with the TRY macro. If
ER_throwVar
is called anywhere in the TRY block, even in a called subroutine,
execution is immediately transferred to the ONERR block.
Within the ONERR block, the error number thrown in the TRY block is available
in local int variable
errCode
. Code in the ONERR block can test
errCode
to
determine what kind of error occurred and take appropriate action. Variable
errCode
, because it is local to the ONERR block, cannot be referenced outside
the ONERR block.
Execution in the ONERR block flows through the end of the block to the
ENDTRY
macro. Alternatively, code in the ONERR block may execute the PASS
macro to throw the error on up to the next higher enclosing TRY block or call
ER_throwVar
with a different error number to raise another exception.
TRY blocks can be nested.
10.5. Cleaning Up
Many times you want to catch errors so you can clean up after the code which
threw the error. If, for example, your app needs to allocate several memory
handles, but any of them could fail because of low memory conditions, your app
should release the handles which were successfully allocated before passing the
memory error on up to the system error handler. Otherwise your app will leak
memory.
volatile HANDLE h1 = H_NULL, h2 = H_NULL, h3 = H_NULL;
TRY
h1 = HeapAllocThrow(BUF1_SIZE);
h2 = HeapAllocThrow(BUF2_SIZE);
h3 = HeapAllocThrow(BUF3_SIZE);
ONERR
HeapFreeIndir(&h1);
HeapFreeIndir(&h2);
PASS;
ENDTRY