Outputting Messages
It can be useful to include in debug versions of a program lines of code that output helpful messages instead of perhaps failing without a word of explanation. You can use writeln statements, but the OutputDebugString procedure demonstrated below offers the following advantages:
- The debug output is sent to the event log so is separated from the rest of the program output.
- The event log can accept large amounts of output, which can be saved readily.
- If left in the final program, which will be run directly (rather than within the Delphi or Lazarus IDE), the user will not see the messages.
The next section describes the use of try ... except code, where the program will output a useful diagnostic message when a runtime error occurs. Also related are the messages that you can supply during your validation of input.
Program InsertionSort2 is intended to sort arrays of negative or positive numbers. The weird output follows the code. The OutputDebugString procedure is in the Windows unit.
program InsertionSort2; {$APPTYPE CONSOLE} {$DEFINE DEBUG} uses SysUtils, Windows; var PosNums : array[1 .. 16] of integer = (503, 087, 512, 061, 908, 170, 897, 275, 653, 426, 154, 509, 612, 677, 765, 703); NegNums : array[1 .. 16] of integer = (-503, -087, -512, -061, -908, -170, -897, -275, -653, -426, -154, -509, -612, -677, -765, -703); procedure Display(iArray : array of integer); var Count : integer; begin for Count := 0 to high(iArray) do write(iArray[Count] : 5); writeln; end; procedure Sort(var intArray : array of integer); var Inserted : Boolean; Current, Insert, Temp : integer; begin if high(intArray) < 1 then begin writeln('No sorting possible'); end else begin for Insert := 1 to high(intArray) do begin Inserted := False; Current := Insert; Temp := intArray[Insert]; while not inserted do begin if Temp > intArray[Current - 1] then begin Inserted := True; //Position found; intArray[Current] := Temp; end else begin //Copy integer to the next position in the array intArray[Current] := intArray[Current - 1]; {$IFDEF DEBUG} outputDebugString(PChar('Copying ' + intToStr(intArray[Current - 1]))); {$ENDIF} dec(Current); end; end;//while end;//for end;//if end;//proc begin writeln('Initial array of positive numbers:'); Display(PosNums); Sort(PosNums); writeln('Sorted array of positive numbers:'); Display(PosNums); writeln('Initial array of negative numbers:'); Display(NegNums); Sort(NegNums); writeln('Sorted array of negative numbers:'); Display(NegNums); readln; end.
It is not difficult to spot mistakes in the output of the "sorted" negative numbers:

Faulty output

Error message
Our extract from the big log file shows that the integers that we are copying are certainly not as intended!

Extract from log file
Once we correct the code in the same way as for program InsertionSort1 at the end of the Displaying Values section of this tutorial, the output and event log are as expected.