Using the C Math Library | ![]() ![]() |
Example - Defining Try/Catch Blocks (ex6.c)
The following example adds try and catch blocks to the example program introduced in the previous section (page 8-3).
You can find the code for this example in the <matlab>/extern/examples/cmath
directory, on UNIX systems, or the <matlab>\extern\examples\cmath
directory, on PCs, where <matlab>
represents the top-level directory of your installation. See Building Stand-Alone C Applications in Chapter 2 for information on building the examples.
/* ex6.c */ #include <stdio.h> #include <stdlib.h> /* Used for EXIT_SUCCESS */ #include <string.h> #include "matlab.h" static double data[] = { 1, 4, 2, 5, 3, 6 }; main() { mxArray *mat0 = NULL; mxArray *mat1 = NULL; mxArray *volatile mat2 = NULL; /* 1 */ mlfEnterNewContext(0,0); mlfAssign(&mat0, mlfDoubleMatrix(2, 3, data, NULL)); mlfAssign(&mat1, mlfDoubleMatrix(3, 2, data, NULL)); mlfTry /* 2 */ { mlfAssign(&mat2, mlfRdivide(mat1, mlfScalar(0))); /* 3 */ mlfPrintf("Return to try block after warning.\n"); mlfPrintMatrix(mlfPlus(mat0, mat1)); } mlfCatch /* 4 */ { mlfPrintf("In catch block. Caught an error: "); /* 5 */ mlfPrintMatrix(mlfLasterr(NULL)); } mlfEndCatch /* 6 */ mlfPrintf("Now in application after catch block.\n"); mxDestroyArray(mat0); /* 7 */ mxDestroyArray(mat1); mxDestroyArray(mat2); mlfRestorePreviousContext(0, 0); return(EXIT_SUCCESS); }
The numbered items in the list below correspond to the numbered comments in the code example:
block must be declared as volatile
. When a variable is declared as volatile
, it is not stored in a register. You can, therefore, assign a value to the variable inside the try block and still retrieve the value.
mlfTry
macro defines the beginning of the try block.
mlfPlus
with two input matrices of unequal size.
mlfCatch
macro defines the beginning of the catch block.
In my catch block. Caught an error:
, and then prints out the message associated with the last error by passing the return value of the mlfLastErr()
routine to the mlfPrintMatrix()
routine.
mlfEndcatch
macro marks the end of the catch block.
mat0
, mat1
, and mat2
, which were used as input arguments to mlfPlus()
and mlfRdivide()
.
The program produces this output.
WARNING: Divide by zero. Return to try block after warning. In catch block. Caught an error: Matrix dimensions must agree. Now in application after catch block.
A more sophisticated error handling mechanism could do much more than simply print an additional error message. If this statement were in a loop, for example, the code could discover the cause of the error, correct it, and try the operation again.
![]() | Customizing Error Handling | Replacing the Default Library Error Handler | ![]() |