12.2.2 產生一個資源保護塊
Delphi提供了一個保留字finally,用於實現資源的保護:
{分配資源}
try
{資源使用情況}
finally
{釋放資源}
end;
try…finally…end就形成了一個資源保護塊。finally後面的語句是在任何情況下,不論程序是否發生異常,都會執行的。
對於(12.2.1)中的例子如下代碼即可確保所分配內存資源的釋放:
var
APointer : Pointer ;
AInt , ADiv : Integer;
begin
ADiv := 0;
GetMem ( APointer , 1024 );
try
AInt := 10 div ADiv ;
finally
FreeMem ( Apointer , 1024 );
end;
end;
下面的例子摘自(6.4)節,是在文件拷貝中實現文件資源的保護:
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;
程序的具體解釋見 (6.4)節。
在異常保護的情況下,當異常發生時,系統會自動彈出一個消息框用於顯示異常的消息。退出當前模塊後異常類自動清除。