Write a Delphi application that does not cause resource allocation to crash
The key is to ensure that if resources are allocated to the program, even if a fault occurs
The occupied resources should also be released.
Files, memory, Windows resources, and objects must be added from time to time.
Pay attention to the resources to be released. In the following event control code example
The memory is allocated first, and then an error occurs, causing it to stop executing.
Code for releasing memory:
Proceduretform1.buttonlclick (Sender: tobject
);
VaR
Pointer1: pointer;
Integer1, numzero: intger;
Begin
Numzero: Limit 0;
Getmem (pointer1, 1024); {allocate 1 kb of memory resources}
Integer1: Limit 5divnumzero; {This sentence produces a division error.
Mistake}
Freemem (pointer1, 1024); {this sentence will not be executed
Row} end;
Although most errors are not so obvious, the previous example contains important
One point: when an error occurs, the program runs out of the module and the subsequent resource release
Program code is no longer executed. To ensure that freemem in the above example can
To release the memory resources occupied by getmem, you must put the code into a resource.
Protection module.
The following figure shows the format of a qu-type resource protection module:
{Resource Allocation}
Try
{Resource usage}
Finally
{Resource release}
End;
The above try... finally module can make the program always execute fi
Any program code in the nally part, even if there is an error in the protection module
. When an error occurs when executing a code in the try part
To the finally part. If no errors are generated during execution
The program is executed in normal order.
In the following event control code example, the memory is allocated first, and then
An error is generated, but the program code for memory release is still executed:
Proceduretform1.button1click (Sender: tobject
);
VaR
Pointer1: pointer;
Integer1, numzero: integer;
Begin
Numzero: Limit 0;
Getmem (pointer1, 1024); {allocate 1 kb of memory resources}
Try
Integer1: Limit 5divnumzero; {This sentence produces a division error.
Mistake}
Finally
Freemem (pointer1, 1024); {this sentence will still be executed
Row}
End;
End;
How to ensure the release of resources used by the program is one in programming
Very important issues, must be put into practice and attention in programming.