Catch Exceptions in MEX Function - MATLAB & Simulink (original) (raw)

Main Content

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 MATLABsqrt function. The catch block handles thematlab::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()) }));
}