Delphi program uses resources release

zhaozj2021-02-11  257

Write a Delphi application that does not cause resource allocation crash

The key is to make sure if resources are allocated in the program, even if the fault occurs, the process

The order should also be able to release the resource occupied.

Files, memory, Windows resources, and objects are some must be added

Take note to ensure the release of the resource. The following event control code example

Allocate memory first, then generate an error, resulting in it no longer execute

Release the program code:

Proceduretform1. Buttonlclick (Sender: TOBJECT

);

VAR

POINTER1: POINTER;

Integer1, Numzero: Intger;

Begin

Numzero: κ0;

GetMem (Pointer1,1024); {assign 1K memory resources}

Integer1: κ5divnumzero; {This sentence gives a division wrong

error}

FreeMem (Pointer1, 1024); {here this sentence will not be held

} END;

Although most errors will not be obvious, the above example contains important

One point: After the error is generated, the program executes the jump out of the module, and the subsequent resource is released.

The extension code is no longer executed. In order to ensure the freemem in the above example

Release the memory resources occupied by GetMem, you must put the code in a resource

Protection module.

Here is a format of a curved resource protection module:

{Resource allocation}

Try

{Resource use}

Finally

{Release of resources}

END;

The above TRY. . . Finally module allows programs to perform Fi

Any program code in the nally section, even if there is an error in the protection module

Produce. When a code in the TRY section is executed, it is an error.

The line will jump directly to the Finally section; if there is no error in the execution,

The program is executed in normal order.

In the following event control code example, the memory is allocated, then produces

I have a mistake, but still executing the programs code that releases the memory:

Proceduretform1. Button1click (Sender: Tobject

);

VAR

POINTER1: POINTER;

Integer1, Numzero: Integer;

Begin

Numzero: κ0;

GetMem (Pointer1,1024); {assign 1K memory resources}

Try

Integer1: κ5divnumzero; {This sentence gives a division wrong

error}

Finally

Freemem (Pointer1,1024); {here this sentence will still be executed

Row}

END;

END;

How to ensure the release of the resources used, in the programming

A very important issue must be practiced and noticed in programming.