Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I put a try-finally block after every Object.Create?

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?

like image 422
markus_ja Avatar asked May 27 '10 16:05

markus_ja


People also ask

Is finally block always executed?

A finally block always executes, regardless of whether an exception is thrown.

Why do we need Finally in try catch?

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.

Which of the following statements about a finally block is true?

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 {}.


1 Answers

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.

like image 159
Frank Shearar Avatar answered Sep 29 '22 09:09

Frank Shearar