Error:Scheme:(exception division by zero)

From IPRE Wiki
Jump to: navigation, search

Cause

This error occurred because a number was divided by zero.

Solution

Find the area of code that makes the division, and prevent it from dividing by zero. You could test to see if the denominator is zero before attempting to do the division.

For example, consider the following code:

(letrec ((total 0)
         (mylist '(2 6 1 5 3))
         (sum (lambda (list)
               (if (null? list)
                   0
                   (+ 1 (car list) (sum (cdr list)))))))
   (set! total (sum mylist))
   (/ total (length mylist)))

That would work fine, given that list. But what if the list were empty:

(letrec ((total 0)
         (mylist '())
         (sum (lambda (list)
               (if (null? list)
                   0
                   (+ 1 (car list) (sum (cdr list)))))))
   (set! total (sum mylist))
   (/ total (length mylist)))

Then, count would be zero, and would cause this error. But, we could check to see if it is zero:

(letrec ((total 0)
         (mylist '(2 6 1 5 3))
         (sum (lambda (list)
               (if (null? list)
                   0
                   (+ 1 (car list) (sum (cdr list)))))))
   (set! total (sum mylist))
   (if (not (= (length mylist) 0))
       (/ total (length mylist))
       (print "Sorry, can't take the average of zero numbers!")

Then, if the list were empty, the code would not crash.