Dealing with errors: try catch throw error ERROR

### 12.4.12 Dealing with errors: try catch throw error ERROR

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.

try tryblock catch symbol catchblock

If tryblock doesn’t produce an error, then

catch symbol catchblock

If tryblock does produce an error, then a string describing the error is assigned to symbol, and catchblock is evaluated.

#### Examples

- The command
  [[1,1]]*[[2,2]]
  produces an error saying Error: Invalid dimension. However,

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

  will not produce an error:
  Output:
  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;
  }

  Input:
  test([[2],[2]])
  Output:

  This produced a product.
  [4]

  with the text in the pane above the output line.
  Input:
  test([[2,2]])
  Output:

  This produced an error Error: Invalid dimension The input is returned.
  [[2,2]]

  with the text in the pane above the output line.

  You can produce your own string to describe an error message with the throw command.
  error and ERROR are synonyms for throw.

  - throw takes one argument:
    str, a string describing an error.
  - throw(str) generates an error with error string str, possibly to be caught by catch.

  #### Example

  With the program:

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

  Input:

  f(12)

  Output:

  12

  since 12 is an integer.
  Input:

  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. Consider the program:

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

  then:
  Input:

  g(12)

  Output:

  12

  since 12 is an integer.
  Input:

  g(1.2)

  Output:

  0

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