Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 36 ยท Classes and Properties

Interfaces and Exceptions

Define Object Pascal interfaces with reference counting, then handle errors with try..except, try..finally, custom exception classes and raise, with a runnable C model.

This lesson covers two features that decide how robust a Delphi program is. Interfaces describe what an object can do without saying what class it is, and they free themselves when nobody uses them any more. Exceptions separate the normal path of your code from error handling, and try..finally guarantees cleanup.

Interfaces

An interface is a list of methods with no fields and no code. A class that implements it promises to provide every method:

PASCAL
type
  IGreeter = interface
    ['{7D3B6A52-1C0E-4F4A-9B61-0D4E3C2A1F10}']
    function Greet(const Name: string): string;
  end;

  TEnglishGreeter = class(TInterfacedObject, IGreeter)
  public
    function Greet(const Name: string): string;
  end;

  TSpanishGreeter = class(TInterfacedObject, IGreeter)
  public
    function Greet(const Name: string): string;
  end;

function TEnglishGreeter.Greet(const Name: string): string;
begin
  Result := 'Hello, ' + Name;
end;

function TSpanishGreeter.Greet(const Name: string): string;
begin
  Result := 'Hola, ' + Name;
end;

By convention interface names start with I. The long string in square brackets is a GUID, which lets you use the as and Supports operators; the IDE generates one with Ctrl+Shift+G. TInterfacedObject is a ready-made base class that implements IInterface and does the reference counting for you.

Code can now work with IGreeter alone:

PASCAL
procedure SayHello(const G: IGreeter);
begin
  WriteLn(G.Greet('Ana'));
end;

var
  G: IGreeter;
begin
  G := TSpanishGreeter.Create;
  SayHello(G);          // Hola, Ana
  G := TEnglishGreeter.Create;
  SayHello(G);          // Hello, Ana
end.                    // no Free anywhere

No Free is needed: an interface variable holds a reference count. Assigning increments it, and when a variable goes out of scope or is reassigned, it decrements; at zero, the object destroys itself. This is why interfaces are popular for objects with unclear owners.

Never mix the two worlds. If you hold a class variable (TSpanishGreeter) and an interface variable pointing at the same object, the interface counter can free the object while the class variable still holds the address. Create the object straight into an interface variable and use only the interface after that.

Use Supports(Obj, IGreeter, G) to ask "can this object do that?" without a hard cast. Interfaces also give you something classes cannot: a class may implement many interfaces, while it can inherit from only one parent class.

Exceptions

An exception is an object raised when something goes wrong. Code that cannot continue calls raise, and the program jumps to the nearest handler up the call chain, skipping the lines in between.

PASCAL
function Divide(A, B: Integer): Integer;
begin
  if B = 0 then
    raise EArgumentException.Create('B must not be zero');
  Result := A div B;
end;

begin
  try
    WriteLn(Divide(10, 0));
  except
    on E: EArgumentException do
      WriteLn('Bad argument: ', E.Message);
    on E: Exception do
      WriteLn('Something else: ', E.ClassName);
  end;
end.

Handlers are tried top to bottom, so put the most specific class first. All exception classes descend from Exception. Some of the classes you meet: EConvertError (StrToInt('abc')), EDivByZero, EAccessViolation (using a nil object), EInOutError (file problems), EOutOfMemory.

Do not write an empty handler: except end; swallows every error, including your own bugs. Handle what you can fix, and let the rest travel up. Inside except, a bare raise; re-raises the current exception after you log it.

try..finally: cleanup that always runs

PASCAL
Stream := TFileStream.Create('data.bin', fmOpenRead);
try
  ReadAll(Stream);
finally
  Stream.Free;
end;

The finally part runs whether the try block ends normally, with an exception, or through Exit or break. It does not handle the exception: after the finally runs, the exception keeps travelling. So you often nest the two forms:

PASCAL
try
  try
    DoWork;
  finally
    Cleanup;
  end;
except
  on E: Exception do
    ShowMessage(E.Message);
end;

Your own exception classes

Exceptions are classes, so derive your own to carry meaning:

PASCAL
type
  EInsufficientFunds = class(Exception)
  strict private
    FShortBy: Currency;
  public
    constructor Create(AShortBy: Currency);
    property ShortBy: Currency read FShortBy;
  end;

constructor EInsufficientFunds.Create(AShortBy: Currency);
begin
  inherited CreateFmt('Short by %m', [AShortBy]);
  FShortBy := AShortBy;
end;

By convention names start with E. Callers can then catch EInsufficientFunds specifically and read ShortBy. The exception object is freed automatically after the handler finishes, so never free it yourself.

How it works: a model in C

C has no exceptions, but setjmp/longjmp can model the control flow. The runnable program keeps a stack of "handlers". TRY records a jump point, RAISE jumps to the newest one, and the cleanup code (the finally part) is written to run on both paths. It also shows a toy reference counter that frees an object when the count reaches zero.

C Stand-in: raise, except, finally and a ref count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The file is released even though divide jumped out of the block, and the shared object is destroyed exactly when its last reference is released: the two guarantees you rely on in Delphi.

Good habits

  • Raise exceptions for exceptional failures (bad file, bad input), not as normal control flow.
  • Never swallow exceptions silently; log or re-raise.
  • Put Free calls in finally.
  • Prefer interfaces when ownership is unclear, and class references when the owner is obvious.
  • In destructors, do not raise: a destructor that fails can leak everything else.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An object is held only by interface variables. When is it destroyed?

    Interface references are counted; the object destroys itself when the count drops to zero.
  2. 2. What does the finally part of try..finally do with an exception?

    finally is for cleanup only. To stop an exception you need an except block.
  3. 3. In except on E: Exception do ... on E: EConvertError do ... what goes wrong?

    Handlers are checked in order, and Exception matches every exception class, so specific handlers must come first.
  4. 4. How many interfaces can a class implement?

    A class has one parent class but may list any number of interfaces.

Summary

  • Interfaces describe behavior without fixing a class; TInterfacedObject supplies reference counting.
  • Use either class references or interface references to one object, not both.
  • raise signals an error; try..except handles it with on E: Class do; order handlers specific to general.
  • try..finally runs cleanup on every path and does not stop the exception.
  • Derive your own E... classes to carry error details.

Next: Text Files and TStringList