Is there a way to "catch" errors in GAP?

283 Views Asked by At

Suppose I'm using a package function f that takes a single argument x and performs some error checking on that argument. Like, is x of the right type? Etc. And if there is an error then f(x) throws an error with Error().

Is there an easy way to write a wrapper function fCatch around f to catch that error, and say return false if f(x) throws an error but true otherwise? The naïve way to accomplish this same effect would be to copy the code for f and change all the Error(...); lines into a return false; and set a return true; at the end, but it's bad form to duplicate all the error-checking code.

1

There are 1 best solutions below

10
Mike Pierce On

As per Alexander Konovalov's comment, the following works, except the Error(...) message that f(x) triggers still prints.

fCatch := function(x)
local result;
    BreakOnError := false;
    result := CALL_WITH_CATCH(f, [ x ])[1];;
    BreakOnError := true;
    return result;
end;

A warning: the CALL_WITH_CATCH function, and any other function with an ALL CAPS name, is undocumented and intended to only be used internally in GAP.