RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.Assert Function

Tests whether a Boolean expression is true.

Pascal
procedure Assert(expr: Boolean); overload;
procedure Assert(expr: Boolean; const msg: string); overload;
C++
Assert(Boolean expr);
Assert(Boolean expr, const AnsiString msg);

In Delphi code, use Assert as a debugging tool to test that conditions assumed to be true are never violated. Assert provides an opportunity to intercept an unexpected condition and halt a program rather than allow execution to continue under unanticipated conditions. 

Assert takes a Boolean expression and an optional message string as parameters. If the Boolean test fails, Assert raises an EAssertionFailed exception. If a message string was passed to Assert, the exception object is created with that string. Otherwise it is created with a default string indicating that the assertion failed. The message is displayed along with the complete path, filename, and the line number on which Assert failed. 

The SysUtils unit causes runtime errors to be turned into exceptions. If SysUtils is not used anywhere in your application, you will get a runtime error 227 rather than an EAssertionFailed exception. This runtime error will halt the program. 

Because assertions are not usually used in shipping versions of a product, compiler directives are provided to disable the generation of assertion code: 

$ASSERTIONS ON/OFF(long form) 

$C +/-(short form) 

These are global switches that affect the entire source file where they occur, regardless of their position in the file. It is not possible to enable and disable assertions for something smaller than a source file. Assertions are on by default.  

Delphi Examples: 

 

{
This example exercises the System Assert function.  The first
call passes and the second call fails.
}

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  TStorage = class(TObject)
    FData: string;
    property Data: string read FData write FData;
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure ModifyStorage(AStorage: TStorage; const s: string);
begin
  Assert(AStorage <> nil, '');
  AStorage.Data := s;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Storage: TStorage;
begin
  Storage := TStorage.Create;
  try
    ModifyStorage(Storage, 'Hello world');
  finally
    Storage.Free;
  end;

  // The following call is buggy and triggers the Assert
  ModifyStorage(nil, 'Ooops');
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!