An exception handler is code that handles a specific exception or exceptions that occur within a protected block of code. However, there are times when you do not need to handle the exception, but you do have code that you want to execute after the protected block, even if an exception occurs. Typically, such code handles cleanup issues, such as freeing resources that were allocated before the protected block.
By using finally blocks, you can ensure that if your application allocates resources, it also releases them, even if an exception occurs. Thus, if your application allocates memory, you can make sure it eventually releases the memory, too. If it opens a file, you can make sure it closes the file later. Under normal circumstances, you can ensure that an application frees allocated resources by including code for both allocating and freeing. When exceptions occur, however, you need to ensure that the application still executes the resource-freeing code.
Some common resources that you should always be sure to release are:
procedure TForm1.Button1Click(Sender: TObject); var APointer: Pointer; AnInteger, ADividend: Integer; begin ADividend := 0; GetMem(APointer, 1024);{ allocate 1K of memory } AnInteger := 10 div ADividend;{ this generates an exception } FreeMem(APointer, 1024);{ this never gets called because of the exception} end;
void __fastcall TForm1::Button1Click(TObject* Sender) { int ADividend = 0; void *ptr = malloc(1024); // allocate 1K of memory; int AnInteger = 10/ADividend; // this generates an exception free(ptr); // this never gets called because of the exception }
Although most errors are not that obvious, the example illustrates an important point: When an exception occurs, execution jumps out of the block, so the statement that frees the memory never gets called.
To ensure that the memory is freed, you can use a try block with a finally block.
For details on writing finally blocks, see Writing a Finally Block.
Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
|
What do you think about this topic? Send feedback!
|