Friday, 27 September 2013

Delphi Assert Function - A Debugging Tool in Delphi

Delphi Assert Function - A Debugging Tool in Delphi

Assert function in Delphi is used as a debugging tool. Assert Function is used to make sure that certain conditions which are assumed to be true are never violated. Assert is a Symbol not a Keyword in Delphi. You can set Assertion ON/OFF in RAD Studio.

Syntax of Assert Function:

function Assert(expr : Boolean [; const msg: string]);

Assert function tests whether a boolean expression expr is true. If not, Assert raises an EAssertionFailed exception. If a message string was passed to Assert, the exception object is created with that string (Exception.CreateFmt).

Assert provides an opportunity to intercept an unexpected condition and halt a program rather than allow execution to continue under unanticipated conditions.

Code Snippet for Assert Function

procedure TestAssert;
var
  i : integer;
begin
   i:=5;
   assert(i<2,'Assert Message');
end;

Now when you run the above Delphi code with Assertions enabled, you will get message 'Assert Message' because 'i<2' is false. If i = 1, the program will continue as nothing happened.

ASSERT is not a KEYWORD in DELPHI

Assert is not a keyword in Delphi. Assert is the symbol that is not reserved by the compiler. Assert exists as symbol within the "System" unit namespace. You can create your own Assert procedure or function and even though it's not recommended, it will compile.

Assertion Settings in Delphi

We can put settings in the RAD Studio to tell the compiler whether to compile with assertions in a debug mode or not. Assertion are always "ON" in debug mode and "OFF" in release mode by default. Compiler directives are provided to disable the generation of assertion code: $ASSERTIONS ON/OFF(long form) 

No comments:

Post a Comment