Debug Run-Time Errors

If you encounter run-time errors in your MATLAB® functions, the run-time stack appears in the MATLAB command window. Use the error message and stack information to learn more about the source of the error, and then either fix the issue or add error-handling code. For more information, see Viewing Errors in the Run-Time StackHandling Run-Time Errors.

Viewing Errors in the Run-Time Stack

About the Run-Time Stack

The run-time stack is enabled by default for MEX code generation from MATLAB. To learn more about the source of the error, use the error message and the following stack information:

  • The name of the function that generated the error

  • The line number of the attempted operation

  • The sequence of function calls that led up to the execution of the function and the line at which each of these function calls occurred

Example Run-Time Stack Trace.  This example shows the run-time stack trace for MEX function mlstack_mex:

Index exceeds matrix dimensions.  Index
value -1 exceeds valid range [1-4] of
array x.

Error in mlstack>mayfail (line 31)
y = x(u);

Error in mlstack>subfcn1 (line 5)
switch (mayfail(u))

Error in mlstack (line 2)
y = subfcn1(u);

The stack trace provides the following information:

  • The type of error.

    ??? Index exceeds matrix dimensions.
    Index value -1 exceeds valid range [1-4] of array x.

  • Where the error occurred.

    Error in ==>mlstack>mayfail at 31
    y = x(u);

  • The function call sequence prior to the failure.

    Error in ==> mlstack>subfcn1 at 5
    switch (mayfail(u))
    Error in ==> mlstack at 2
    y = subfcn1(u);

When to Use the Run-Time Stack

To help you find the source of run-time errors, the run-time stack is useful during debugging. However, when the stack is enabled, the generated code contains instructions for maintaining the run-time stack, which might slow the run time. Consider disabling the run-time stack for faster run time.

Disable the Run-Time Stack.  You can disable the run-time stack by disabling the memory integrity checks as described in How to Disable Run-Time Checks.


Before disabling the memory integrity checks, verify that all array bounds and dimension checking is unnecessary.

Handling Run-Time Errors

The code generator propagates error IDs. If you throw an error or warning in your MATLAB code, use the try-catch statement in your test bench code to examine the error information and attempt to recover, or clean up and abort. For example, for the function in Example Run-Time Stack Trace, create a test script containing:

    % Add your error handling code here
For more information, see The try/catch Statement (MATLAB).