RAD Studio |  |

Writing finally Blocks
See Also
Collapse All

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:

- Files
- Memory
- Windows resources or widget library resources (Qt objects)
- Objects (instances of classes in your application)

The following event handler illustrates how an exception can prevent an application from freeing memory that it allocates:
Copy Code

    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;

Copy Code

    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.

See Also

Writing Exception Handlers

Writing the Try Block

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!