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.

The numbered items in the list below correspond to the numbered comments in the code example:

  1. Variables that will be set within a try 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.
  2. mlfTry macro defines the beginning of the try block.
  3. The exampe deliberately triggers a warning, by attempting to divide by zero, and an error, by calling mlfPlus with two input matrices of unequal size.
  4. The mlfCatch macro defines the beginning of the catch block.
  5. The error handling code in this catch block is quite simple. It displays a message, 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.
  6. The mlfEndcatch macro marks the end of the catch block.
  7. After the catch block completes executing, the application continues, freeing the matrices, mat0, mat1, and mat2, which were used as input arguments to mlfPlus() and mlfRdivide().

The program produces this output.

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