Saturday, 4 August 2012

Division by Zero in ABAP

ABAP has a strange behaviour when division by zero is considered.

Mathematically: Division by zero is undefined. Also all the other programming languages raise an exception when a number is divided by 0.

However ABAP has a strange an unexpected behavior in this regard.

ABAP raises an exception CX_SY_ZERODIVIDE  when any number is divided by 0 but not when the dividend is also 0.

Example:

CASE I
data :  dividend type i value 10.
data :  divisor   type i value 0.
data :  answer type i.

answer = dividend / divisor.  ->> Raises an exception CX_SY_ZERODIVIDE.

 CASE II
data :  dividend type i value 0.
data :  divisor   type i value 0.
data :  answer type i.

answer = dividend / divisor.  ->> No exception raised

answer  will contain 0 as a result.

This is an arbitrary behaviour of ABAP and coders should take care to handle this situation in their code.

The runtime error associated with the zero divide exception is BCD_ZERODIVIDE.