12.2.2 generates a resource protection block
Delphi provides a reserved word finally, which is used to achieve resource protection:
{Allocating Resources}
Try
{Resource Usage}
Finally
{Releasing Resources}
End
The Try...finally...end form a resource protection block. Finally, the following statement is executed in any case, regardless of whether the program has an exception.
For the example in (12.2.1), the following code ensures the release of the allocated memory resources:
Var
Apointer:pointer;
Aint, Adiv:integer;
Begin
Adiv: = 0;
Getmem (Apointer, 1024);
Try
Aint: = ten div adiv;
Finally
Freemem (Apointer, 1024);
End
End
The following example is taken from section (6.4), which protects file resources in a copy of a file:
Procedure CopyFile (const FileName, destname:tfilename);
Var
Copybuffer:pointer;
TimeStamp, Bytescopied:longint;
Source, Dest:integer;
Destination:tfilename;
Const
Chunksize:longint = 8192;
Begin
Destination: = Expandfilename (Destname);
If hasattr (destination, fadirectory) then
Destination: = destination + ' + ' + extractfilename (FileName);
TimeStamp: = Fileage (FileName);
Getmem (Copybuffer, chunksize);
Try
Source: = FileOpen (FileName, fmsharedenywrite);
If Source < 0 Then
Raise Efopenerror.create (Fmtloadstr (Sfopenerror, [FileName]));
Try
Dest: = filecreate (destination);
If Dest < 0 Then
Raise Efcreateerror.create (Fmtloadstr (sfcreateerror, [destination]));
Try
Repeat
Bytescopied: = Fileread (Source, copybuffer^, chunksize);
If bytescopied > 0 Then
FileWrite (Dest, copybuffer^, bytescopied);
Until Bytescopied < chunksize;
Finally
FileClose (Dest);
End
Finally
FileClose (Source);
End
Finally
Freemem (Copybuffer, chunksize);
End
End
The specific interpretation of the procedure is shown in section (6.4).
In the case of exception protection, when an exception occurs, the system automatically pops up a message box to display the message for the exception. The exception class is automatically cleared after exiting the current module.