Main Content

Catch Exceptions in MEX Function

To override the default error behavior, you can catch exceptions thrown in MEX functions when calling MATLAB® functions.

This code causes MATLAB to throw an exception because it defines the input argument incorrectly for the MATLAB sqrt function. The catch block handles the matlab::engine::MATLABException by displaying the string describing the exception in the MATLAB command window.

ArrayFactory factory;
std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();

// Variable with no value causes error
std::vector<matlab::data::Array> arg;
try {
    matlab::data::Array result = 
        matlabPtr->feval(u"sqrt", arg);
}
catch (const matlab::engine::MATLABException& ex) {
    matlabPtr->feval(u"disp", 0, std::vector<Array>({factory.createScalar(ex.what()) }));
}

Related Topics