Exception Handling

Exceptions are the primary way that SAX event consumers communicate to event producers; this is the reverse of the typical communication pattern (from producer to consumer). We’ll look at SAX exceptions before we delve more deeply into either producers or consumers. We’ll look at the several types of exceptions that might be thrown, the error handler interface that lets your code decide how to handle errors, and then how these normally fit together.

Keep this rule of thumb in mind: when a SAX handler throws any exception—including a java.lang.RuntimeException or a java.lang.Error—parsing stops immediately. The exception passes through the parser and is thrown by XMLReader.parse(). Beyond some possible additional error reports, the only additional event callback should be ContentHandler.endDocument(). This method is always called before parsing finishes, even after errors, to ensure it can be used for cleaning up. (That callback is presented in Chapter 4, in Section 4.1.1.)

SAX2 Exception Classes

There are four standard exception classes, with a common base class used in the signature for all handler methods. The parse() methods, as well as the EntityResolver class presented in Section 3.4 in Chapter 3, can also throw java.io.IOException to indicate problems unrelated to XML text content. You will find that many XML APIs are declared the same way; for example, JAXP parser methods may throw such exceptions even if they don’t expose SAX events directly. See ...

Get SAX2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.