Great quote destructors in Delphi development…
Posted by jpluimers on 2019/12/18
No destructor should ever throw an exception. If it does, there’s not really any way to recover from it anyway, so it doesn’t matter if anything leaks because of it.
Greate quote by [WayBack] User Rob Kennedy answering [WayBack] interface – Avoiding nested try…finally blocks in Delphi – Stack Overflow
It’s a basic development pattern for writing Delphi destructor code.
–jeroen
thaddy said
Bit late, but:
try
.. some code
finally
.. some finalization starts here
try
.. try it
except
— if we have an exception, handle it
end;
— here are the usual free’s
end;
jpluimers said
Thanks!
Lars Fosdal said
I sometimes do a
try
…
finally
Inherited
end
in my destructor
thaddy said
It is actually wrong.
As long is the exception is handled correctly inside the except block: but that is the essense of the pattern anyway.
jpluimers said
Can you elaborate on this? Obviously I miss your point, so there is a learning opportunity ahead (:
Navid said
Maybe something like this (run in console and echo %errorlevel% should report 0):
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes;
type
TToDo = class
private
FCallBeforeLeaving: TNotifyEvent;
public
constructor Create(const CallToMake: TNotifyEvent);
destructor Destroy; override;
end;
{ TContained }
constructor TToDo.Create(const CallToMake: TNotifyEvent);
begin
FCallBeforeLeaving := CallToMake;
end;
destructor TToDo.Destroy;
begin
try
FCallBeforeLeaving(Self);
except on E: Exception do
Writeln(‘And I got away, …’);
end;
inherited;
end;
var
WontCall: TToDo;
begin
WontCall := TToDo.Create(nil);
try
Writeln(‘I”ll get away with this …’);
finally
WontCall.Free;
end;
end.