Product SiteDocumentation Site

9.3. Try-Catch expressions

A try catch expression evaluates the expression inside the try block and returns its resulting value.
However, if an error is raised during this evaluation, the catch clause is evaluated and its result value returned.
Example 9.7. A try catch expression.
try { 1 div 0 } catch * { "Caught!" } 
Results:
"Caught!"

Only errors raised within the lexical scope of the try block are caught.
Example 9.8. An error outside of a try-catch expression (failing).
let $x := 1 div 0
return try { $x }
catch * { "Caught!" } 
Error:
division by zero

Errors that are detected statically within the try block, for example syntax errors, are still reported statically.
Note that this applies also if the engine is capable of detecting a type error statically, while another engine might only discover it at runtime and catch it. You should keep this in mind, and only use try-catch expressions as a safety net.
Example 9.9. A try catch expression with a syntax error (failing).
try { x } catch * { "Caught!" } 
Error:
invalid expression: syntax error, a path expression cannot 
begin with an axis step

Example 9.10. A try catch expression with a type error (no guarantee of failure or success).
try { "foo" + "bar" } catch * { "Caught!" }
Results:
"Caught!"