Yes I want to read a simple a logfile into a TStringList and that is easy done with LoadFromFile. But the problem is that the file can be already opened by another program at the same time so an exception may appear. I have tried to use:

Do not call Destroy directly in an application. Instead, call Free, which checks that the TFileStream reference is not nil and only then calls Destroy.
–
inzKulozikJan 16 '09 at 18:43

You are rigth it should be Free not Destroy ...
–
DrejcJan 19 '09 at 10:03

1

Correction: Destroy is quite acceptable in the above example. MyObject.Free is equivalent to if MyObject <> nil then MyObject.Destroy. The reason you use Free is to provide a check whether the reference has been assigned. In the above example you can safely guarantee that by reaching line 3 that fileStream references an object that was correctly created. What is missing however (an much more of an issue) is the try..finally statement. Also, depending on the scope of the fileStream variable, it may be advisable to clear it: finally fileStream.Destroy; fileStream := nil; end;
–
Craig YoungDec 18 '09 at 12:51

I was always somehow confused why there are two methods available, and honestly I almost in every case use Destroy over Free. This is because it will throw an exception in cases I have not assigned the object and so bugs are faster detected.
–
DrejcFeb 11 '10 at 8:11

Yes I know. But I want to search many log-files in a directory. If I have a try except for every file load maybe it slow down the execution. It is already rather slow... /Roland
–
Roland BengtssonJan 15 '09 at 7:18

1

You actually want a try / finally for every file. Unless you are reading a lot of really small files I don't see it impacting performance significantly. If it does, then you may want to consider a different mechanism all together.
–
Jim McKeethJan 15 '09 at 9:51

@Niklas: NO! NO! NO! and NO again! Do not abuse try..except! Hiding errors with try..except leads to a huge amount of insidious bugs in the long run.
–
Craig YoungDec 18 '09 at 12:56

1

@Craig Young: Did you miss the part of my answer that says "...and tell the user about the problem that arises"? That is not hiding errors, that is handling them gracefully in my book.
–
Niklas WindeJan 13 '10 at 12:58