[DUG] Related try..finally question

Conor Boyd Conor.Boyd at trimble.co.nz
Fri Jul 21 15:12:00 NZST 2006


All good info, thanks.

C. 

-----Original Message-----
From: delphi-bounces at ns3.123.co.nz [mailto:delphi-bounces at ns3.123.co.nz]
On Behalf Of Paul Heinz

Conor wrote:

> It gets a bit verbose, but IMHO the correct form is as follows:
>
> Something := TSomething.Create(nil);
> Try
> 	X := TX.Create(blah); //for some reason crashes here
> 	Try
> 		Y := TY.Create();
> 		Try
> 			//Do Something
> 		Finally
> 		   FreeAndNil(y); //will throw exception (?) because was
never 
> created
> 		End;
> 	Finally
> 		FreeAndNil(X);
> 	End;
> finally
>    FreeAndNil(Something);
> End;

This approach whilst leak safe, requires a fair bit more typing when the
object count get up but also adds a lot of exception frame handling code
and metadata to your method. Assigning nil to all objects and then a
single finally block is both less typing and has smaller and faster code
size.

Admittedly, if you follow Dennis's suggestion for 'try except around
Free'
in your finally for paranoid long-lived server code, you're adding back
the exception handling frames and meta data again but at least it's
buying you something in terms of leak safety.

Mind you, if the Free's in your finally's are causing exceptions
themselves (i.e. exceptions inside Destroy usually), I'd say your server
app is likely mortally wounded anyway and into the cascading exceptions
limbo state of no return (like the Delphi IDE get into from time to time
:-)



More information about the Delphi mailing list