The Try-Catch Expression is another welcome addition to the XML Query Language. This page introduces the expression and provides some examples.
XQuery 1.0
While the first version of the xquery language provided the possibility to raise errors, the language had no standard mechanism to handle these errors. The following two queries show how it works:
results in "XPTY0004: can not be an operand for +"
results into "Could not locate collection: /db/not-existent/"
For a long time eXist-db provided a custom mechanism to handle these errors with the function. An example:
Additional information about the error can be obtained from two variables which are set by the function:
For more details check the eXist-db function documentation.
XQuery 3.0
In version 3.0 of XQuery language the handling of errors has become part of the language: the try-catch expression. An introduction example:
The "catch error list" specifies wich errors are handled in the next catch expression; the asterix wildcard is an special example meaning all errors match.
It is possible to have more catch clauses, the values in the catch-error-list determines which catch block is executed.
The following query is a nice complete example of the try-catch expression. The outcome of the query is 2
:
The java exception of the second example can be handled as well:
Finally it is possible to raise and handle an xquery error using the function:
For more details check the examples in the specification and in the corresponding usecases. These examples are integrated into our test suite.
The expression is available starting eXist-db 1.5 ; in Jan 2012 changes were made to reflect the latest specification