typestar

Raising your own exception in Delphi

An overdraft rule that raises its own exception class, caught where the withdrawals happen.

program RaiseCustom;
uses SysUtils;
type
  EOverdraft = class(Exception);  // a domain error of your own
procedure Withdraw(Balance, Amount: Double);
begin
  if Amount > Balance then
    raise EOverdraft.CreateFmt('short by %.2f', [Amount - Balance]);
  WriteLn(Format('paid %.2f, %.2f left', [Amount, Balance - Amount]));
end;
begin
  try
    Withdraw(120.00, 45.00);
    Withdraw(75.00, 90.00);  // breaks the rule, so the guard raises
  except
    on E: EOverdraft do      // the caller decides what the rule means
      WriteLn('declined: ' + E.Message);
  end;
end.

How it works

  1. EOverdraft = class(Exception) declares a domain error that adds nothing to its parent.
  2. raise EOverdraft.CreateFmt('short by %.2f', [Amount - Balance]) formats the message as it raises.
  3. The caller's on E: EOverdraft do handler prints E.Message after the first withdrawal succeeded.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
536
Tokens
107
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 92 seconds.

Type this snippet

Step 3 of 3 in Exceptions, step 24 of 27 in Language basics.

← Previous Next →