| Using the C Math Library | ![]() |
Error Handling Overview
The MATLAB C Math library routines handle error conditions in two ways, depending on the severity of the error:
The following example program illustrates this default library error handling. The program deliberately causes a warning-level error condition, division by zero, and a more severe error condition, attempting to add two matrices of unequal size, that causes termination.
#include <stdio.h>
#include <stdlib.h> /* used for EXIT_SUCCESS */
#include <string.h>
#include "matlab.h"
/* Matrix data. Column-major element order */
static double data[] = { 1, 2, 3, 4, 5, 6 };
main()
{
/* Declare matrix variables */
mxArray *mat0 = NULL;
mxArray *mat1 = NULL;
mxArray *mat2 = NULL;
mlfEnterNewContext(0,0);
/* Create two matrices of different sizes */
mlfAssign(&mat0, mlfDoubleMatrix(2, 3, data, NULL));
mlfAssign(&mat1, mlfDoubleMatrix(3, 2, data, NULL));
/* Division by zero will produce a warning */
mlfAssign(&mat2, mlfRdivide(mat1, mlfScalar(0)));
mlfPrintf("Return to application after warning.\n");
/* Adding mismatched matrices produces error */
mlfPrintMatrix(mlfPlus(mat0, mat1));
mlfPrintf("Should not be reached after error.\n");
/* Free any matrices that were assigned to variables */
mxDestroyArray(mat2);
mxDestroyArray(mat0);
mxDestroyArray(mat1);
mlfRestorePreviousContext(0, 0);
return(EXIT_SUCCESS);
}
This program produces the following output. You can see how this program continues processing after a warning, but terminates after an error.
WARNING: Divide by zero. Return to application after warning. ERROR: Matrix dimensions must agree. EXITING
| Handling Errors and Writing a Print Handler | Customizing Error Handling | ![]() |