Mega Code Archive

 
Categories / Delphi / System
 

Conditional debugging using Assert

Title: Conditional debugging using Assert Question: Do you know the problem of inserting debugging code in your program, and then having to spend a long time getting it out again? Wouldn`t it be cool if all your debugging code vanished from your program once you were done using it? Well, there IS a way, and it doesn`t have to be compiler directives, with conditional compiles... Answer: I recently ran across an article at borland.com about using the Assert() method. Since I had never heard of this method I was fairly impressed. What happens is this - instead of writing your code with OutputDebugString, logging to a text file or other things to debug your running applicaion and trying to figure out exactly where the error occured, you have this inbuild function called Assert which tells you what you wanted to know. It is very simple to use: Assert(expression); If the expression returns false, assert throws an exception called EAssertionFailed, and the exception message is something like: Assertion Failed (C:\src\unit1.pas, line 34) Then it is very easy to use in your programs, and when you don't want these checks any more, you use the {$ASSERTIONS OFF} or {$C-} compiler directive. This is simply a piece of text you write in your unit. This you include in all the files where you don't what the assertions to be active. To remove assertions from the entire project, use the compiler option at Project Options | Compiler | Assertion and turn it off. When assertion is turned off, all your code in Assert statements is not included in your project, and it is as lean and fast as ever. Talk about easy debugging :) Another benefit is that you only have to keep one version of your source, so that you don't have a debugging version and a public version... /Laust Rud Jensen