I have written this piece of code:
FD := TList<double>.Create;
FN := TList<double>.Create;
RemList := TList<double>.Create;
dati := TStringList.Create;
try
try
//code
except
on E : Exception do
ShowMessage('Incorrect values. Error: ' + E.Message);
end;
finally
if Assigned(dati) then
dati.Free;
if Assigned(FD) then
FD.Free;
if Assigned(FN) then
FN.Free;
if Assigned(RemList) then
RemList.Free;
end;
I am using firemonkey so I won't have problems when I'll run this on mobile devices because ARC will manage the lifetime. But is this code safe when I am on windows?
I have read that I cannot have a finally and a catch all together so I need to have a nested try block. I guess that the best way is this:
FD := TList<double>.Create;
try
FN := TList<double>.Create;
try
RemList := TList<double>.Create;
try
//and so on...
finally
Rem.Free;
end;
finally
FN.Free;
end;
finally
FD.Free;
end;
Here I am sure that I'll free the object in any case and in a safe way but the code is hard to read. I have seen that Marco Cantu is suggesting the 2nd approach in object pascal handbook and I understand it, but in my case I want to avoid it.
Can something wrong happen in the first block of code I have written?