Nice Approach For Exception Safe Code

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

function MyFunction: TMyObject;
begin
  Result := TMyObject,Create;
  Result.DoSomething;
end;

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:

function MyFunction: TMyObject;
begin
  Result := TMyObject,Create;
  try
    Result.DoSomething;
  except
    on E: Exception do
    begin
      Result.Free;
      raise;
    end;
  end;
end;

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

function MyFunction: TMyObject;
begin
  Result := TMyObject,Create;
  try
    Result.DoSomething;
  except
    on E: Exception do
    begin
      FreeAndNil(Result);
      raise;
    end;
  end;
end;

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:

function MyFunction: TMyObject;
var
  lMyObject: TMyObject;
begin
  lMyObject := TMyObject,Create;
  try
    lMyObject.DoSomething;
    Result := lMyObject;
    lMyObject := nil;
  finally
    lMyObject.Free;
  end;
end;

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.