bhylu.com

Advertisements

XML XQuery Error Handling

try/catch can turn a known dynamic error into a deliberate result. Catch the error you expect rather than masking every failure as a successful empty report.

How it works

A malformed count is different from a packet with zero stock. This query deliberately converts invalid numeric text so the failure path is visible and reproducible. The err namespace identifies standard error codes. In an application, validate input before constructing reports and keep unexpected exceptions available for diagnosis. A broad fallback that hides missing files, invalid queries and wrong types can produce plausible but incorrect reports.

Run the code

Use Saxon-HE 12.9 with Java 21 or newer. Download the official Java distribution, keep its dependency JARs in a lib folder, and save exchange.xml beside the example. On Windows the command is java -cp "lib/*" net.sf.saxon.Query -s:exchange.xml -q:query-errors.xq !method=text. Use your actual Saxon JAR folder; the official archive may put dependencies in a nested lib directory, so include both folders in the Java classpath when needed. Saxon-HE does not supply XSD schema-aware processing or the XQuery Update Facility.

Download the complete query-errors.xq source. Keep each lab in its own folder. Sources are served as text, not as public executable server scripts. Review the starting setup.

Example

query-errors.xq

xquery version "3.1";
declare namespace err="http://www.w3.org/2005/xqt-errors";
try { xs:integer("several") }
catch err:FORG0001 { "Rejected non-numeric quantity" }

Expected result

Rejected non-numeric quantity

The known lexical conversion error is caught and labelled as a rejection. The result is a message for the lab, not an accepted stock value. Other errors are not swallowed by this specific catch.

Check the exact contract in the XML specification, XPath 1.0, the XSD 1.0 primer, lxml validation documentation and Saxon’s processor documentation.