Some commands produce errors, and if your program tries to run such a command it will halt with an error. The try and catch commands help you avoid this. They to use them, put potentially problematic statements in a block following try, and immediately after the block put catch with an argument of an unused symbol, and follow that with a block of statements that can deal with the error.
If tryblock doesn’t produce an error, then
If tryblock does produce an error, then a string describing the error is assigned to symbol, and catchblock is evaluated.
Examples.
| try {[[1,1]]*[[2,2]]} |
| catch (err) { |
| print("The error is " + err) |
| } |
| test(x):= { |
| local y, str, err; try { y:= [[1,1]]*x; str:= "This produced a product.";} |
| catch (err) |
| {y:= x; |
| str:= "This produced an error " + err + " The input is returned.";} |
| print(str); |
| return y; |
| } |
| This produced a product. |
| [4] |
| This produced an error Error: Invalid dimension The input is returned. |
| [[2,2]] |
You can produce your own string to describe an error message with the
throw command.
error and ERROR are synonyms for throw.
Example.
With the program:
| f(x):= { |
| if (type(x) != DOM_INT) |
| throw("Not an integer"); |
| else |
| return x; |
| } |
Input:
Output:
| 12 |
since 12 is an integer.
Input:
will signal an error
since 1.2 in not an integer.
You can catch this error in other programs. Consider the program:
| g(x):= { |
| try(f(x)) catch(err) {x:= 0;} |
| return x; |
| } |
then:
Input:
Output:
| 12 |
since 12 is an integer.
Input:
Output:
| 0 |
since 1.2 is not an integer, f(x) will give an error and so g(x) will return 0.