Wednesday, October 13, 2010

How to prevent the error 'Division by zero'

Since the early days of programming, the dreaded 'Division by zero' error exists.

And there is no exception in Dynamics Ax.



So if you're gonna write code like A = B /C, you better make sure that C holds a value.
Of course you can do a check with a simple if-statement (if C then A = B/C), but there is an easier way. You can use minOne, a method that exists in the Global class.


Example:

myvalueA = myvalueB / minOne(myvalueC);


Definition of minOne:

If myvalueC holds a value (is not zero), it's value is returned. If it is zero, the value 1 is returned.
So better be safe then sorry and spare your users the error message (and execution stop).




PS: I know it has been very quite on this blog the last couple of months.
As you can see, I'm not dead. Nor am I planning on ending my blog, I've just been very busy with other stuff. Thanx for your patience.

2 comments:

  1. This will not give you same result. Mathematically anything divided by zero should be zero. But if you use minOne you will get the B as output.

    ReplyDelete
    Replies
    1. This isn't entirely correct. Anything divided by zero is indeterminate: https://en.wikipedia.org/wiki/Division_by_zero
      Its the reason why division by zero causes an error.

      Delete