Macaulay2 » Documentation
Packages » Macaulay2Doc » The Macaulay2 language » error handling » try
next | previous | forward | backward | up | index | toc

try -- catch an error

Description

The return value is the value returned by y or z, as the case may be.

i1 : apply(-3..3, i -> try 1/i then 1/i else infinity)

        1    1                   1  1
o1 = (- -, - -, -1, infinity, 1, -, -)
        3    2                   2  3

o1 : Sequence

The clause then y may be omitted, in which case the return value is the value returned by x if there is no error or alarm.

i2 : apply(-3..3, i -> try 1/i else infinity)

        1    1                   1  1
o2 = (- -, - -, -1, infinity, 1, -, -)
        3    2                   2  3

o2 : Sequence

The clause else z may be omitted, in which case the return value is the value returned by y, unless an error or alarm occurs, in which case null is returned.

i3 : apply(-3..3, i -> try 1/i then 1/i)

        1    1           1  1
o3 = (- -, - -, -1, , 1, -, -)
        3    2           2  3

o3 : Sequence

The clauses then y else z may both be omitted, in which case the return value is the value returned by x, unless an error or alarm occurs, in which case null is returned.

i4 : apply(-3..3, i -> try 1/i)

        1    1           1  1
o4 = (- -, - -, -1, , 1, -, -)
        3    2           2  3

o4 : Sequence

In the alternate form try x then y except err do z, x is first evaluated. If no error occurs, then the value of y is returned, or the value of x if the then y clause is omitted. If an error occurs, then the corresponding Error object is assigned to the symbol specified by err. That symbol is then available during the evaluation of z, whose value is returned.

i5 : apply(-3..3, i -> try 1/i then 1/i except err do err)

        1    1                           1  1
o5 = (- -, - -, -1, division by zero, 1, -, -)
        3    2                           2  3

o5 : Sequence
i6 : apply(-3..3, i -> try 1/i except err do err)

        1    1                           1  1
o6 = (- -, - -, -1, division by zero, 1, -, -)
        3    2                           2  3

o6 : Sequence
i7 : oo#3

o7 = division by zero

o7 : Error

The behavior of interrupts (other than alarms) is unaffected.

Caveat

We will change the behavior of this function soon so that it will be possible to catch errors of a particular type. Meanwhile, users are recommended to use this function sparingly, if at all.

See also

For the programmer

The object try is a keyword.


The source of this document is in /build/reproducible-path/macaulay2-1.26.05+ds/M2/Macaulay2/packages/Macaulay2Doc/ov_language.m2:777:0.