Current location - Education and Training Encyclopedia - Education and training - DELPHI Basic Course: Exception Handling and Program Debugging (1) [4]
DELPHI Basic Course: Exception Handling and Program Debugging (1) [4]
Generate resource protection block

Delphi finally provides a reserved word to protect resources.

{Assign resources}

attempt

{Resource usage}

finally

{Publish Resources}

End;

Try…finally…end forms a resource protection block. Whether the program is abnormal or not, the statement after finally will be executed in any case.

For the example in (), the following code can ensure that allocated memory resources are released.

defined variable

APointer: pointer;

AInt ADiv:Integer;

begin

ADiv:=;

GetMem(apo int)

attempt

AInt:= div ADiv;

finally

Free memory

End;

End;

The following example is taken from section (), which is used to protect file resources in file replication.

Process copy file (constant file name DestName: TFileName)

defined variable

CopyBuffer: pointer;

Timestamp bytes copied:Longint;;

Source Dest: integer;

Target: TFileName

constant

chunk size:Longint =;

begin

destination:= expand filename(DestName)

If HasAttr (destination directory), then

Destination: = Destination+\+Extract file name (file name)

Time stamp: = file size (file name)

GetMem(CopyBuffer ChunkSize)

attempt

Source := FileOpen (file name fmShareDenyWrite)

If the source < then

Throws efopenerror create (fmtloadstr (sfopenerror [file name]).

attempt

Dest := FileCreate (destination)

If Dest & lt then

Raises efcreateerrorcreate (fmtloadstr (sfcreateerror [destination]))

attempt

repeat

BytesCopied := FileRead (source CopyBuffer^ block size)

If BytesCopied & gt then

File write (target CopyBuffer^ byte copy)

Until bytes copied < chunksize.

finally

File Close (Target)

End;

finally

File Close (Source)

End;

finally

FreeMem(CopyBuffer ChunkSize)

End;

End;

For a detailed description of this process, see section ().

In the case of exception protection, when an exception occurs, the system will automatically pop up a message box to display the exception message, and the exception class will be automatically cleared after exiting the current module.

Back to the directory DELPHI basic tutorial

Editor's recommendation

Java programming training video tutorial

J EE advanced framework actual combat training video tutorial

Development and actual combat of Visual C++ audio and video technology

Oracle indexing technology

ORACLE G database development optimization guide

Performance optimization of Java programs makes your Java programs faster and more stable.

C embedded programming design mode

Practical guide to Android game development

Lishi Xinzhi/Article/program/Delphi/20 13 1 1/25 194