### 25.4.1 Handling errors

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 can help you to avoid halting the program; 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 handle the error.

try tryblock catch (symbol) catchblock

If tryblock does not produce an error, then the code

catch (symbol) catchblock

is not reached. Otherwise, if tryblock does produce an error, then a string describing the error is assigned to symbol, and catchblock is evaluated.

#### Examples

The command below produces an error:

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

Error: Invalid dimension |  |  |  |  |  |  |  |  |  |

However, the following command does not produce an error:

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

The error is — Error: Invalid dimension

1 |  |  |  |  |  |  |  |  |  |

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]])

| “This produced a product.” |  |  |  |  |  |  |  |  |

⎡ ⎣ | 4 | ⎤ ⎦

with the text in the pane above the output line.

test([[2,2]])

| “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 catch this error in other programs. Consider the program:

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

then:

g(12)

12 |  |  |  |  |  |  |  |  |  |

since 12 is an integer. With a non-integer input, f(x) gives an error and so g(x) returns 0:

g(1.2)

0 |  |  |  |  |  |  |  |  |  |