Best practice to do nested TRY / FINALLY statement

前端 未结 6 1027
逝去的感伤
逝去的感伤 2020-12-04 16:07

Hi What is the best way to do nested try & finally statements in delphi?

var cds1  : TClientDataSet;
    cds2  : TClientDataSet;
    cds3  : TClientDataS         


        
6条回答
  •  鱼传尺愫
    2020-12-04 16:40

    There's another variation of the code without nested try ... finally that just occurred to me. If you don't create the components with the AOwner parameter of the constructor set to nil, then you can simply make use of the lifetime management that the VCL gives you for free:

    var
      cds1: TClientDataSet;
      cds2: TClientDataSet;
      cds3: TClientDataSet;
      cds4: TClientDataSet;
    begin
      cds1 := TClientDataSet.Create(nil);
      try
        // let cds1 own the other components so they need not be freed manually
        cds2 := TClientDataSet.Create(cds1);
        cds3 := TClientDataSet.Create(cds1);
        cds4 := TClientDataSet.Create(cds1);
    
        ///////////////////////////////////////////////////////////////////////
        ///      DO WHAT NEEDS TO BE DONE
        ///////////////////////////////////////////////////////////////////////
    
      finally
        cds1.Free;
      end;
    end;
    

    I'm a big believer in small code (if it's not too obfuscated).

提交回复
热议问题