I have a general question about best practice in OO Delphi. Currently, I put try-finally blocks anywhere I create an object to free that object after usage (to avoid memory leaks). E.g.:
aObject := TObject.Create;
try
aOBject.AProcedure();
...
finally
aObject.Free;
end;
instead of:
aObject := TObject.Create;
aObject.AProcedure();
..
aObject.Free;
Do you think it is good practice, or too much overhead? And what about the performance?
A finally block always executes, regardless of whether an exception is thrown.
The code that will possibly throw an exception is enclosed in the try block and catch provides the handler for the exception. The finally block executes the code enclosed in it regardless of whether the exception is thrown or not.
The finally block is called regardless of whether or not the related catch block is executed. Option C is the correct answer. Unlike an if-then statement, which can take a single statement, a finally statement requires brackets {}.
It's definitely best practice to use try-finally.
In the event of an exception being raised, that object will be freed.
As for performance: measure before you optimise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With