Pascal: Division by Zero; Try..Except

program ex20;
const num = 34;
var   i: integer

begin
for i:=5 downto -5 do
  writeln (num, ' / ', i, ' = ', num / i);
end.

When the backwards counter reaches 0 a division by zero error is generated and the program terminates. How could the program be improved?

We can use this example to illustrate the idea of assertions and loop invariants. You should try to ensure that a loop works properly, to verify its integrity - does it work with different sets of data, does it always terminate and produce the correct result? Exhaustive testing can be time-consuming so we use loop invariants and assertions. Every loop has two parts, a fixed or invariant part, which ensures that the loop terminates when a specific condition is met, and a variable part whose change ensure that the loop eventually terminates. 

The invariant can be described in the code as a comment just inside the beginning of the loop. An assertion is a logical statement which is always true after execution of the loop. The assertion comes at the end of a loop and its truth must not be changed by the loop. 

The invariant in the case above is that num is a numeric constant so does not change, i is a counter which counts backwards and should always be <> 0 (to avoid the error), and the output of num/i will always be less than its value in the previous cycle. By defining the loop invariant in this way we would avoid the pitfall of the division by zero. The assertion after the loop would be that num/i is <>0, a condition which will fail if i=0. 

To avoid the error we need to trap the condition divisor = 0.

for i:=5 downto -5 do
 try
  writeln (num, ' / ', i, ' = ', num / i:8:2);
  except on EZeroDivide do  
//or use EDivByZero
   writeln ('Cannot divide by zero');
 end;

Back to questions