Nice Approach For Exception Safe Code

Maybe everyone knows the issue with code that is not exception safe. Let’s see an example:

The function MyFunction returns an instance of an object which is normally no problem. But MyFunction creates the instance and then runs further code. And in case of an exception no one “cares” about the instance and you will simply get a memory leak.

That’s why people normally avoid functions that return instances or write the code in an exception safe way:

At this point some purists would say that the Result should also be assigned to nil after it had been destroyed.

I don’t want to start a long discussion about FreeAndNil but what people, including myself, don’t like is to catch an exception in order to raise it again a moment later.

Instead the code could be written with a try-finally-block:

The tricks are:

  1. Free can be called if an instance is nil.
  2. Finally is always called.
  3. After assigning the Result no further code that could cause an exception is called.
This entry was posted in Delphi, FireMonkey, RAD Studio 10 Seattle, RAD Studio 10.1 Berlin, RAD Studio 10.2 Tokyo, RAD Studio XE5, RAD Studio XE6, RAD Studio XE7, RAD Studio XE8, Tips and Tricks. Bookmark the permalink.

7 Responses to Nice Approach For Exception Safe Code

  1. Fritz says:

    These code is wrong….. you are always destroying the object.

     

  2. Fritz says:

    Forget my comment, please now i have seen it….

  3. Unfortunately this only helps for objects that are created in functions and returned. It won’t help for code like this:

    dataset.Insert;
    try
    dataset[‘bla’] := ‘blub’
    dataset.Post
    except
    dataset.Cancel;
    raise;
    end;

    • roman says:

      Yes, but I think you mean

      Result := TMyDataSet.Create(nil)
      try
      Result.Insert;
      Result[‘bla’] := ‘blub’
      Result.Post
      except
      Result.Cancel;
      FreeAndNil(Result)
      raise;
      end;

      But this code is really ugly, isn’t it?

  4. Bascy says:

    That was my fist reaction too .. 🙂

    It works, but I don’t like it precisely because of that first reaction.. its not very clear from the code what is happening

  5. Stefan Glienke says:

    The entire function in every version is a code smell imo.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.