# saxon:try()

This function is available only in Saxon-SA

This function provides a simple way of recovering from dynamic errors (including type errors). It comes in two forms:

try($arg1 as item()*, $arg2 as function) ==> item()*

This returns the value of the first argument, unless evaluation of the first argument fails. If a failure occurs, then the function identified by the second argument (created using saxon:function) is called, supplying error information as an argument. For example:

    <xsl:template match="/">
      <o>
        <xsl:copy-of select="saxon:try(1 div 0,
                                saxon:function('f:catch-division-error',1))"/>
      </o>
    </xsl:template>

    <xsl:function name="f:catch-division-error">
     <xsl:param name="error-info"/>
     <xsl:sequence select="$error-info"/>
    </xsl:function>

This produces the output:

    <o>
      <error code="FOAR0001"
             namespace="http://www.w3.org/2004/07/xqt-errors"
             module="file:/c:/MyJava/tests/testsuite/saxon/saxon87.xsl"
             line="15">
        <message>Integer division by zero</message>
      </error>
    </o>

The error information is passed to the catch function in the form of an XML document node. This contains a single `<error>` element as its outermost element. The `<error>` element has a `<message>` element child giving the text of the error message, and attributes giving the error code, the namespace of the error code, and the module, line number and column number of the place where the error occurred. Information that is not available is omitted. Further attributes and child elements may be added to this structure in future releases (for example, to provide a stack trace or information about underlying errors.)

If you want to handle some errors but not others, the way to achieve this is to catch all errors, and then re-throw those that you don't want to handle. This can be achieved by calling `error(xs:QName($error-info/error/@namespace, $error-info/error/@code), $error-info/error/message, $error-info)` (The third argument is recognized as being an `<error>` element, and the location information is extracted and placed in the exception that is then thrown.)

try($arg1 as item()*, $arg2 as item()*) ==> item()*

This simpler form of the function returns the value of the first argument, unless evaluation of the first argument fails. If a failure occurs, then the second argument is evaluated and its value is returned.

Here is an example showing the simpler form of call: the expression `saxon:try(1 div 0, "divide by zero")` returns the string "divide by zero".

To recover from failures occurring in XSLT instructions, for example schema validation errors, wrap the instructions in a stylesheet function (`xsl:function`) and call this function within a call of `saxon:try()`.

Next