I have a program, written in C++, which uses WSTP to communicate with Mathematica 10 (i.e., linked using Install["name_program"]
).
How should my code report an internal error? I've read through the WRI docs on Error and Interrupt Handling, but unfortunately they only talk about an instance where there are problems with the connection between the program and Mathematica, which doesn't apply to my case.
Example:
extern "C" int get_number(int param)
{
try
{
//calculate result
return result;
}
catch(...)
{
//What should be here?
}
}
Answer
tl; dr Report errors through return values. MathLink programs can return any Mathematica expression they like which makes structured error handling possible.
It looks like you have a function that returns integers with a template like
:Begin:
:Function: get_number
:Pattern: getNumber[x_Integer]
:Arguments: {x}
:ArgumentTypes: {Integer32}
:ReturnType: Integer32
:End:
Use a Manual
return type instead:
:Begin:
:Function: get_number
:Pattern: getNumber[x_Integer]
:Arguments: {x}
:ArgumentTypes: {Integer32}
:ReturnType: Manual
:End:
Then you can return any expression you like, not just integers:
void get_number(int param) {
...
if (success)
MLPutInteger32(stdlink, result);
else
MLPutSymbol(stdlink, "$Failed");
}
You can return a symbol such as $Failed
or a compound expression with some information about the error, e.g. myPackage`myError[12, "this is an error"]
.
Then instead of exposing getNumber
on the Mathematica side to the user, create a wrapper for it that will handle the return values with pattern matching and whatever is needed on errors, e.g. issue a Message
.
Comments
Post a Comment