The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,861 other subscribers

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 [WayBackUser Rob Kennedy answering [WayBackinterface – Avoiding nested try…finally blocks in Delphi – Stack Overflow

It’s a basic development pattern for writing Delphi destructor code.

–jeroen

6 Responses to “Great quote destructors in Delphi development…”

  1. thaddy's avatar

    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;

  2. I sometimes do a
    try

    finally
    Inherited
    end
    in my destructor

  3. thaddy's avatar

    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's avatar

      jpluimers said

      Can you elaborate on this? Obviously I miss your point, so there is a learning opportunity ahead (:

      • Navid's avatar

        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.

Leave a reply to Navid Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.