Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi variable might not have been initialized warning

I've added some code to my delphi project to interact with the registry, using some tutorials I found online to guide my effort. Every example I've seen seems to use this structure for their registry access:

var
  Registry: TRegistry;
begin
  try
    Registry := TRegistry.Create;
    //additional code to access and use the registry object could go here
  finally
    Registry.Free;
end;

But when I implement my code following that structure, I am getting a warning that my variable Registry may not have been initialized on the line where I free the TRegistry object.

So, I'm wondering whether the examples I've found are just wrong on the right way to access the registry. Should I be calling Free on my TRegistry object regardless of whether the Create succeeeds, and just ignore the warning? Should, instead, my try/finally block only surround the code after the successful constructor call, but not wrap the create call? Something else?

like image 273
Jessica Brown Avatar asked Mar 17 '12 17:03

Jessica Brown


1 Answers

In your code, if TRegistry.Create raises an exception then the Registry variable will not be assigned. And thus the finally will attempt to access an uninitialized variable.

The correct way to write the code is to make sure that the variable is assigned before you enter the try/finally block.

Registry := TRegistry.Create;
try
  //additional code to access and use the registry object could go here
finally
  Registry.Free;
end;

This is the most fundamental lifetime management pattern in Delphi coding and you should commit it deeply to muscle memory.

Note that if the constructor fails, then it will tidy up the partially constructed object before propagating the exception. The new object reference, Registry in this code, is only assigned if the constructor completes successfully.

I would hope that the examples you found were in fact written as per my code above and you somehow transcribed them incorrectly. If they are written as per the question, then they are clearly in error.

like image 161
David Heffernan Avatar answered Sep 25 '22 00:09

David Heffernan