Show: Delphi C++
Display Preferences

Writing a Finally Block (Delphi)

From RAD Studio
Jump to: navigation, search

Go Up to Exception handling Index

Finally blocks are introduced by the keyword finally. They are part of a try..finally statement, which has the following form:

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

In a try..finally statement, 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, which is called the cleanup code. After the finally part executes, the exception handler is called. If no exception occurs, the cleanup code is executed 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:

procedure TForm1.Button1Click(Sender: TObject);
APointer: Pointer;
AnInteger, ADividend: Integer;
  ADividend := 0;
  GetMem(APointer, 1024);{ allocate 1K of memory }
    AnInteger := 10 div ADividend;{ this generates an exception }
    FreeMem(APointer, 1024);{ execution resumes here, 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.

See Also

Personal tools
In other languages