XML Parsing With DOM and Xerces (part 2) - Oops! (
Page 5 of 9 )
If you take a close look at the previous example,
you'll notice some error-handling routines built into it. It's instructive to
examine that, and understand the reason for its inclusion.
You'll remember that I defined a Writer object at the top of my program; this
Writer object provides a convenient way to output a character stream, either to
a file or elsewhere. However, if the object does not initialize correctly, there
is no way of communicating the error to the final JSP page.
The solution to the problem is simple: throw an exception. This exception can
be captured by the JSP page and resolved appropriately.
Let's take another look at the constructor, this time focusing on the error-handling
built into it:
// constructor
public MyFifthDomApp (String xmlFile, Writer out) throws SAXException
{
// some code here
} catch (IOException e) {
throw new SAXException(e);
}
}
Why is this necessary? Because if you don't do this, and your Writer object throws
an error, there's no way of letting the JSP document know what happened, simply
because the Writer object is the only available line of communication between
the Java class and the JSP document. It's a little like that chicken-and-egg situation
we all know and love...
Now, in the JSP page, it's possible to set up a basic error resolution mechanism
to display the error on the screen. In order to test-drive it, try removing one
of the opening "item" tags from the XML document used in this example and accessing
the JSP page again through your browser.
It's also possible to raise a DOMException; however, take a look at what the
Xerces documentation has to say about this:
"DOM operations only raise exceptions in "exceptional" circumstances, i.e., when
an operation is impossible to perform (either for logical reasons, because data
is lost, or because the implementation has become unstable). In general, DOM methods
return specific error values in ordinary processing situations, such as out-of-bound
errors when using NodeList." (from http://xml.apache.org/xerces-j/apiDocs/org/w3c/dom/DOMException.html)