RAD Studio
ContentsIndex
PreviousUpNext
Writing a finally Block (C++)

bcc32 includes extensions to the C++ language that let it use finally blocks as well. Like exception handlers, a finally block must appear directly after the try block, but it is introduced by the__finally keyword instead of catch.

try
{
  // statements that may raise an exception
}
__finally
{
    // statements that are called even if there is an exception in the try block
}

The application always executes any statements in the finally part, even if an exception occurs in the try block. When any code in the try block (or any routine called by code in the try block) raises an exception, execution halts at that point. Once an exception handler is found, execution jumps to the finally part. After the finally part executes, the exception handler is called. If no exception occurs, the code in the finally block executes in the normal order, after all the statements in the try block. 

The following code illustrates an event handler that uses a finally block so that when it allocates memory and generates an error, it still frees the allocated memory:  

void __fastcall TForm1::Button1Click(TObject* Sender)
{
  int ADividend = 0;
  void *ptr = malloc(1024); // allocate 1K of memory;
  try
    int AnInteger = 10/ADividend; // this generates an exception
  __finally
    free(ptr); // this gets called anyway, despite the exception
}

The statements in the finally block do not depend on an exception occurring. If no statement in the try part raises an exception, execution continues through the finally block.

Note: Traditional C++ code does not include support for finally
block. Instead, it tends to use destructors to handle the freeing of resources. However, when working with VCL, which is written in Delphi, finally blocks are an important tool because of the way VCL objects must be allocated on the heap.
Tip: You can also use std::auto_ptr to ensure that allocated objects are deleted.

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