   10.4.9  Dealing with errors

Some commands produce errors, and if your program tries to run such a command it will halt with an error. To avoid this, you can use the try and catch commands. To use these, you put any potentially problematic statements in a block following try, and immediately after the block put catch with an argument of an unused symbol. If the try block doesn’t produce an error, then catch and the block following catch will be ignored. If the try block does produce an error, then a string describing the error is assigned to the argument to catch, and the block following catch is evaluated. For example, the command

[[1,1]]*[[2,2]]

will produce an error saying Error: Invalid dimension. However,

```  try {[[1,1]]*[[2,2]]}
catch (err) {
print("The error is " + err)
}
```

will not produce an error; instead it will print

The error is Error: Invalid dimension

With the following program

```  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;
}
```

if you enter

test([,])

then

This produced a product.

will be printed and the result will be



. If you enter

test([[2,2]])

then

This produced an error Error: Invalid dimension The input is returned.

will be printed and the result will be

[[2,2]]

You can use the throw command (or equivalently, the error or ERROR command) to generate an error and error string, possibly to be caught by catch. The throw command takes as argument a string, which will be used as the error message. For example, suppose you have the program

```  f(x) := {
if (type(x) != DOM_INT)
throw("Not an integer");
else
return x;
}
```

Then

f(12)

will simply return

12

since 12 is an integer, but

f(1.2)

will signal an error

Not an integer Error: Bad Argument Value

since 1.2 in not an integer. You can catch this error in other programs; the program

```  g(x) := {
try(f(x)) catch(err) {x := 0;}
return x;
}
```

will return x is x is an integer, but if x is not an integer, f(x) will give an error and so g(x) will return 0.   