Operators > Programming Operators > Example: Using the try-on-error Programming Operator
  
Example: Using the try-on-error Programming Operator
Use the try-on-error, break, continue and return programming operators to handle error conditions.
1. On the Math Formatting tab, in the Results group, click Show Trailing Zeros.
2. Setup a 6x6 matrix then use the matrix function to set its elements to a known value.
Click to copy this expression
Click to copy this expression
Click to copy this expression
Click to copy this expression
Click to copy this expression
Click to copy this expression
Click to copy this expression
3. Write a program to set a range of elements to a value defined by a function over the given range.
Click to copy this expression
The program fails because when x=0 and y=0 an attempt is made to divide (x+y) by zero.
4. Change the program so that element (0,0) of the new matrix takes on the value of the corresponding element of matrix Z instead of the divide-by-zero value.
Click to copy this expression
Click to copy this expression
The program ensures that element (0,0) is excluded from being set to a divide-by-zero value.
5. Use the try and break operators to capture the error condition and allow the program to run. The error condition, divide by zero, is represented by the string "DBZ".
Click to copy this expression
The on error block is executed only if the try test returns an error.
Click to copy this expression
Mathcad executes the program as follows:
a. The first loop starts with x=0 and y=0.
b. The try operator checks the expression for errors and gets a divide-by-zero error. This tells the program to execute the on error block.
c. The on error block executes its first statement and sets element (0,0) to "DBZ", then the break operator halts the execution of the current loop (x=0, y=0..5). As a result, the remaining row=0 elements remain unchanged.
d. The program jumps to the next x loop (x=1, y=0..5) and, in the absence of other errors, writes the row=1 elements.
e. The program continues to execute the remaining loops until it covers the specified ranges.
6. Replace the break operator with the continue operator and observe the different output.
Click to copy this expression
Click to copy this expression
Unlike the break operator, the continue operator continues to the next iteration of the current loop, and the remaining elements of row=0, and the remaining elements of the matrix, get set to (x+y)/(10x-y) as before.
7. Replace the continue operator with the return operator and observe the different output.
Click to copy this expression
Click to copy this expression
Unlike the continue operator which continues the execution of the current loop, the return operator halts the program and returns Y3 with element (0, 0) set to "DBZ".