StaticCompiler - how to handle integer division error?

StaticCompiler.jl does not allow exceptions. I got stuck trying to compile code involving the mod operator %, as it can raise an exception DivideError if you’re dividing by zero. How can I work around this?

I found a solution. Define a new function

function myrem(a, b)
    b==0 ? 0 : a%b
end

Then replace any a%b in the code by myrem(a, b). This allows the compiler to know that I never call % when b is zero, and I’m able to use StaticCompiler.compile_executable, without getting errors.

Edit: corrected operator name from mod to rem.

3 Likes

You can redefine % within your module if needed. Also you may mean rem rather than mod.

julia> %(a,b) = b == 0 ? 0 : Base.rem(a, b)
% (generic function with 1 method)
1 Like