It all depends on what ode you are working on.  For desktop apps, the
following will be sufficient:


changes := Nil;
issues := Nil;
terrorists := Nil;
try
  changes := TStringList.create;
  issues := TIssuesList.create;
  terrorists := THardToFind.create;

  // stuff is done, planes flown.  That type of things.

finally
  terrorists.free;
  issues.free;
  changes.free;
end;

If any of the creates or code in the middle raises an exception, Free will
be called for all the objects.

But after spending many years writing server type apps, I now do this in the
finally block:

finally
  try
    terrorists.free;
  except
    // Code to handle the exception
  end;


  try
     issues.free;

  except
    // Code to handle the exception
  end;

  try
    changes.free;

  except
    // Code to handle the exception
  end;
end;

The main issue here is of any of the Free raises an exception, one or more
objects can be left un-freed, causing a memory leak which is not only hard
to find, but will eventually cause the server to crash with an out of memory
error.  Furthermore, wrap the whole lot in a try -- except block to catch
all exceptions and handle them gracefully.

----- Original Message -----
From: "Nahum.Wild" <[EMAIL PROTECTED]>
To: "'NZ Borland Developers Group - Delphi List'" <[EMAIL PROTECTED]>
Sent: Thursday, March 04, 2004 3:36 PM
Subject: [DUG] try..finally : Which way is best?


> Ok so this is something that has bugged me for ages, partly because I
don't
> know and partly because I can't be bother trying to figure it out.
>
> is the following code ok? or should I give each it's own try..finally?
>
> --
>
> changes := TStringList.create;
> issues := TIssuesList.create;
> terrorists := THardToFind.create;
> try
>
> // stuff is done, planes flown.  That type of things.
>
> finally
>   terrorists.free;
>   issues.free;
>   changes.free;
> end;
>
> --
>
> I mean what could go wrong in the TStringList.create constructor for
> example?  It's not like there should be anything much in there that could
go
> wrong anyway?  Because if it does except the destructor will be
immediately
> called - learnt that one the hard way many years ago.  As a general rule
of
> thumb I don't put anything significant in a constructor for my own
classes -
> that's what init or setup methods are for.
>
> For the record I've never done it this way, I've always given each their
own
> try..finally.
>
> Thoughts anyone?
>
>
>
> Nahum Wild
> Software Innovator & Process Consultant
> IFE
> PayGlobal
>
> _______________________________________________
> Delphi mailing list
> [EMAIL PROTECTED]
> http://ns3.123.co.nz/mailman/listinfo/delphi
>
_______________________________________________
Delphi mailing list
[EMAIL PROTECTED]
http://ns3.123.co.nz/mailman/listinfo/delphi

Reply via email to