Einzelnen Beitrag anzeigen

Benutzerbild von Aphton
Aphton

Registriert seit: 31. Mai 2009
1.198 Beiträge
 
Turbo Delphi für Win32
 
#8

AW: Der Konstruktor ist abgestürzt - Wie gehe ich im Destruktor am besten vor?

  Alt 11. Apr 2013, 16:35
Delphi-Quellcode:
program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TMyBuggyObject = class
    PrivObject1: TObject;
    PrivObject2: TObject;
    constructor Create;
    destructor Destroy; override;
  end;

constructor TMyBuggyObject.Create;
begin
  Writeln('TMyBuggyObject.Create(): Allocating object1');
  PrivObject1 := TObject.Create;
  Writeln('TMyBuggyObject.Create(): Throwing exception');
  raise Exception.Create('TMyBuggyObject.Constructor - selfdestruct');
  Writeln('TMyBuggyObject.Create(): Allocating object2');
  PrivObject2 := TObject.Create;
end;

destructor TMyBuggyObject.Destroy;
begin
  Writeln('TMyBuggyObject.Destroy(): Im being called.');
  Writeln('TMyBuggyObject.Destroy(): PrivObj1=0x' + IntToHex(integer(PrivObject1), 8));
  Writeln('TMyBuggyObject.Destroy(): PrivObj2=0x' + IntToHex(integer(PrivObject2), 8));
  Writeln('TMyBuggyObject.Destroy(): Freeing both!');
  PrivObject2.Free;
  PrivObject1.Free;
  inherited;
end;

procedure main;
var
  Instance: TMyBuggyObject;
begin
  Instance := NIL;
  try
    Instance := TMyBuggyObject.Create;
    try
      Writeln('Maincode: No exception!');
    finally
      Instance.Free;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Writeln('Address of instance:'#9'0x', IntToHex(integer(Instance), 8));
  Readln;
end;

begin
  ReportMemoryLeaksOnShutdown := True;
  main;
end.
Code:
TMyBuggyObject.Create(): Allocating object1
TMyBuggyObject.Create(): Throwing exception
TMyBuggyObject.Destroy(): Im being called.
TMyBuggyObject.Destroy(): PrivObj1=0x00520D10
TMyBuggyObject.Destroy(): PrivObj2=0x00000000
TMyBuggyObject.Destroy(): Freeing both!
Exception: TMyBuggyObject.Constructor - selfdestruct
Address of instance:   0x00000000
das Erkennen beginnt, wenn der Erkennende vom zu Erkennenden Abstand nimmt
MfG
  Mit Zitat antworten Zitat