How do I handle error when parsing an XML file using SAX?

The ErrorHandler interface implemented by the org.xml.sax.helpers.DefaultHandler class provides some methods for error handling mechanism in SAX parsing. The methods are warning(), error(), and fatalError().

package org.kodejava.xml;

import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class SAXErrorHandlerDemo {
    public static void main(String[] args) throws Exception {
        SAXErrorHandlerDemo demo = new SAXErrorHandlerDemo();;

    public void run() throws Exception {
        // Creates the SAXParserFactory and SAXParser instance.
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        // Parse the error.xml file using MySAXHandler as the 
        // DefaultHandler implementation.
        InputStream is = getClass().getResourceAsStream("/error.xml");
        DefaultHandler handler = new MySAXHandler();
        parser.parse(is, handler);

    // Override the error handling methods defined by the ErrorHandler
    // interface. This method will handler exceptions thrown by the
    // parsing process.
    static class MySAXHandler extends DefaultHandler {
        public void warning(SAXParseException e) throws SAXException {
            System.out.println("warning   : " + e.getMessage());

        public void error(SAXParseException e) throws SAXException {
            System.out.println("error     : " + e.getMessage());

        public void fatalError(SAXParseException e) throws SAXException {
            System.out.println("fatalError: " + e.getMessage());

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.