> The XQuery Processor
| TryCatchExpr | ::= | TryClause CatchClause+ |
| TryClause | ::= | "try" "{" TargetExpr "}" |
| CatchClause | ::= | "catch" "(" NameTest ( "," ErrorCode ( "," ErrorDescr ( "," ErrorVal)?)? )? ")" "{" Expr "}" |
| ErrorCode | ::= | "$" VarName |
| ErrorDescr | ::= | "$" VarName |
| ErrorVal | ::= | "$" VarName |
In the following subsection, we present some examples in order to demonstrate the try-catch functionality.
(: Simple try-catch example :) try { 3 + "2" } catch(err:XPTY0004) { "Caught a type error" }
(: try-catch with multiple catch clauses showing catch clause precedence :) try { 3 + 2 > "30" } catch(err:XQDY0004) { "Some random error that does not occur" } catch(*, $code) { concat("Caught ", $code) } catch(err:XPTY0004) { "This is the error throw. But it should be caught in the catch clause above" }
(: Use of the description variable in the catch clause :) try { 2 + "3" } catch(*, $ecode, $desc) { string-join(($ecode, $desc), " ") }
(: Nested try-catch with the use of the error object :) try { for $x in (1, 2, 3, "4", 5) return try { $x + 4 } catch(err:XPTY0004) { fn:error(xs:QName("err:XPTY0004"), "Rethrowing the exception", $x) } } catch(*, $code, $desc, $obj) { string-join(("An error was caught: ", $code, "Description:", $desc, " The cause was:", $obj), " ") }
(: try-catch catching error happening inside functions :) declare function local:squares() { for $x in (1, 2, 3, 4, "5", 6, 7) return $x * $x }; try { local:squares() } catch(err:XPTY0004) { "Caught a type error" }
let $x := 1 div 0 return try { $x } catch (*) { "This catch clause won't fire." }