Search code examples
javamathimage-processingclojuredivide-by-zero

Handling division by zero in graphics code


I'm writing a library for procedural image generation (Clisk) which allows users to define their own mathematical functions to generate images.

It's clearly possible for them to define a function which could result in a divide by zero for some pixels, e.g. (pseudocode)

red = 1.0 / (xposition - 0.5)

This would result in a divide by zero whenever xposition = 0.5 (the middle of the image)

Ideally I don't want image generation to crash... but at the same time I don't want to create a clunky hack to ignore divide by zeros that will cause problems later.

What would be a good, robust, systematic approach to handling these cases?


Solution

  • Ideally I don't want image generation to crash... but at the same time I don't want to create a clunky hack to ignore divide by zeros that will cause problems later.

    (I'm assuming you mean the snippet to be an example of some user-supplied code ...)

    Clearly, if the user-supplied code could throw exceptions, then you can't stop that happening. (And the advice to check before division is obviously irrelevant ... to you.)

    So what could you do apart from "crash"? Generate an empty image? Ignore the user's function? You'd be producing garbage ... and that's not what the user needs.

    You certainly can't reach in and fix his / her java code. (And if that snippet is meant to be code written in some custom language, then you can't reach in and correct that either. You / your library doesn't know what the user-supplied code should be doing ...)

    No. I reckon that the best answer is to wrap any unexpected (unchecked) exceptions coming out of the user-supplied code in an exception of your own that tells the user clearly that the error occurred in his code. It is then up to the application code calling your library code whether to deal with the exception or "crash".


    If you are asking for a "good, robust, systematic approach" for users to write their functions, I think you are barking up the wrong tree. And it is not really your concern ...