Write a Delphi application that does not crash resource allocation
The key is to ensure that if resources are allocated in the program, even when a failure occurs, the program
The program should also be able to release occupied resources.
Files, memory, WINDOWS resources and objects are some that must be added from time to time
Take care to ensure that resources are released. In the following event control code example
Memory is allocated first, and then an error occurs, causing it to no longer execute.
Program code to release memory:
PROcedureTForm1. ButtonlClick(Sender:Tobject
);
Var
Pointer1: Pointer;
Integer1,Numzero:Intger;
begin
Numzero:Κ0;
GetMem(Pointer1, 1024); {Allocate 1K memory resources}
Integer1: Κ5divNumzero; {This sentence generates a division error
error}
FreeMem (Pointer1, 1024); {This sentence will not be executed here
OK}end;
Although most errors are not this obvious, the above example contains important
One point: when an error occurs, the program execution jumps out of the module, and subsequent resources are released.
The program code is no longer executed. To ensure that FreeMem in the above example can
To release the memory resources occupied by GetMem, the code must be put into a resource
protection module.
Here is the format of a curved resource protection module:
{Allocation of resources}
try
{Use of resources}
finally
{Release of resources}
end;
The above try. . . The finally module enables the program to always execute fi
??nally any program code in the section, even if there is an error in the protected module
produced in. When a piece of code in the try section causes an error when executed, execute
The line will jump directly to the finally section; if no errors occur during execution, then
Programs are executed in normal order.
In the following event control code example, memory is allocated first and then
An error occurred, but the program code that released the memory was still executed:
ProcedureTForm1. Button1Click(Sender:Tobject
);
Var
Pointer1: Pointer;
Integer1,Numzero:Integer;
begin
Numzero:Κ0;
GetMem(Pointer1, 1024); {Allocate 1K memory resources}
try
Integer1: Κ5divNumzero; {This sentence generates a division error
error}
finally
FreeMem(Pointer1,1024);{Here this sentence will still be executed
OK}
end;
end;
How to ensure that the program releases the resources used is an important issue in programming.
This is a very important issue that must be practiced and paid attention to during programming.