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.



4 comments:

  1. Heyy!!

    This just happened to me yesterday! I saw this behaviour in a piece of code.

    I thought I was going crazy!

    Good to know somebody else akwnowledge this too!

    Good job!

    Thanks!

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This is incredibly insane behavior. Both programatically and mathematically.

    If you want to force correct behavior, simply do this:

    Rewrite: ( X / Y )
    As: ( X * ( 1 / Y ) )

    And voila!

    ReplyDelete