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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.