Main Content

mexSetTrapFlag (C and Fortran)

(Removed) Control response of MEXCALLMATLAB to errors

mexSetTrapFlag has been removed. Use mexCallMATLABWithTrap instead. For more information, see Compatibility Considerations.

C Syntax

#include "mex.h"
void mexSetTrapFlag(int trapflag);

Fortran Syntax

subroutine mexSetTrapFlag(trapflag)
integer*4 trapflag



Control flag.

  • 0 - On error, control returns to the MATLAB® prompt.

  • 1 - On error, control returns to your MEX file.


Call mexSetTrapFlag to control the MATLAB response to errors in mexCallMATLAB.

If you do not call mexSetTrapFlag, then whenever MATLAB detects an error in a call to mexCallMATLAB, MATLAB automatically terminates the MEX file and returns control to the MATLAB prompt. Calling mexSetTrapFlag with trapflag set to 0 is equivalent to not calling mexSetTrapFlag at all.

If you call mexSetTrapFlag and set the trapflag to 1, then whenever MATLAB detects an error in a call to mexCallMATLAB, MATLAB does not automatically terminate the MEX file. Rather, MATLAB returns control to the line in the MEX file immediately following the call to mexCallMATLAB. The MEX file is then responsible for taking an appropriate response to the error.

If you call mexSetTrapFlag, the value of the trapflag you set remains in effect until the next call to mexSetTrapFlag within that MEX file or, if there are no more calls to mexSetTrapFlag, until the MEX file exits. If a routine defined in a MEX file calls another MEX file, MATLAB:

  1. Saves the current value of the trapflag in the first MEX file.

  2. Calls the second MEX file with the trapflag initialized to 0 within that file.

  3. Restores the saved value of trapflag in the first MEX file when the second MEX file exits.

Version History

Introduced in R2008b

collapse all

R2018a: mexSetTrapFlag has been removed

The mexCallMATLABWithTrap function, similar to mexCallMATLAB, lets you call MATLAB functions from within a MEX file. In addition, mexCallMATLABWithTrap lets you catch (trap) errors. Using this function for exception handling is more flexible that using mexCallMATLAB with the mexSetTrapFlag function.

Existing MEX files built with mexSetTrapFlag continue to run.