Throwing MException subclass from MEX file

5 views (last 30 days)
Marko Budisic
Marko Budisic on 9 Dec 2014
Commented: Adam on 9 Dec 2014
My code has a particular algorithm which is coded up both as a m-file (slower) and a MEX file (faster). I would like to throw a particular MException subclass (which captures particular information about what went wrong) from both versions of the algorithm (and let the outside function that calls either of them handle it).
Now, this is easy enough to do with throw() from inside the M-file but I am not sure how to do it from inside a MEX file.
My guess was that mexEvalString of called with argument "throw(...);" should have worked but it just returns control to MEX file and "contains" exception within. mexEvalStringWithTrap gets me a pointer to MException object, which I could use to handle the exception within C++ but I don't want to do exception handling without MEX, but rather in an M-file that calls either C++ or Matlab version of the code.
Is there a way around this? I'm running 2014b.

Answers (1)

Adam
Adam on 9 Dec 2014
You could use
mexErrMsgIdAndTxt( "MyProg:Id", "Somoething went wrong.");
in the mex.
Then in a wrapper function that calls the mex catch this in a try catch wrapped around the mex call and then rethrow your MException subclass using the information from this exception.
Personally I use
mexErrMsgTxt(...)
in my code and I can try-catch this, but I don't get an error id which is not ideal. The above version will give you the error id for finer control of the exception types in the C++ code.
  2 Comments
Marko Budisic
Marko Budisic on 9 Dec 2014
The problem with this approach is that instead of just capturing "Something went wrong", I also need to capture the data at the point of error that made it go wrong. I could technically encode the data as a string and pass that out instead "Something went wrong." message, but that seemed kludgy, which is why I started writing my own MException in the first place.
Adam
Adam on 9 Dec 2014
I'm not aware of a way of passing custom classes out of mex other than in struct form via the standard mex outputs, but I haven't done a huge amount in mex so there may be other methods.

Sign in to comment.

Categories

Find more on Software Development Tools in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!