Managing Division by Zero Exceptions Using the DIVIDE Function
Arguably one of the most common arithmetic calculation headaches that most programmers encounter in their programming life is the division by zero scenario. This problem occurs when constructing an expression using the division operator '/' without taking care to check the denominator of the calculation for zeros.
The usual indication that this problem has occured are messages similar to the following in the SAS log.
One way of overcoming this problem is to apply a more defensive approach to our code and use conditional process to detect zeros in the denominator first. Based on this result it should then be possible to apply a business rule to determine what action to perform.
An elegant solution to the problem is to use the DIVIDE function. The DIVIDE function performs the same operation as the '/' operator but with the added benfit of generating special missing values where a result of infinity (.I) or minus infinity (.M) should be returned.
The following code not only results in a clean Log window free of 'Division by Zero' Note messages, but also generates the following special missing values which can be detected and processed directly within data step and proc step code.
data sample_data; input numerator denominator; datalines; 100 2 50 . 60 3 20 0 -100 0 run;
data divide_by_zero; set sample_data; results = divide
For example, the following IF statement would extract rows resulting from a division by zero.
if results in (.I,.M) then output;