user1466695
user1466695

Reputation: 21

Continue the java code at catching the exception

I am writing a java program for parsing an XML file and detecting if its UTF-8 compliant. I've gotten that part working but when it catches the first exception (syntax error) it stops the execution. I want it to find all the errors and not just the first one. Is there any way I can log the errors and not stop it on the first one? Here's my code.

 import java.io.IOException;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;

  //import com.edankert.SimpleErrorHandler;
 public abstract class Wellformed extends DocumentBuilder {

   public static void main(String[] args) {
         try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
             factory.setValidating(false);
             factory.setNamespaceAware(true);

               DocumentBuilder builder = factory.newDocumentBuilder();
               builder.setErrorHandler(new SimpleErrorHandler());

               builder.parse(new InputSource("contacts.xml"));
            } catch (ParserConfigurationException e) {
               e.printStackTrace();
            } catch (SAXException e) {
               e.printStackTrace();
             } catch (IOException e) {
                 e.printStackTrace();
          }

        }
      }

    import org.xml.sax.ErrorHandler;
    import org.xml.sax.SAXParseException;

      public class SimpleErrorHandler implements ErrorHandler {

       public void warning(SAXParseException e) {
      }

          public void error(SAXParseException e) {
           System.out.println(e.getMessage());
         }

          public void fatalError(SAXParseException e) {
           System.out.println(e.getMessage());
         }
     }

Upvotes: 2

Views: 1048

Answers (1)

Attila
Attila

Reputation: 28762

You could write your own ErrorHandler that does not throw and attach that to builder (instead of the SimpleErrorHandler)

Upvotes: 1

Related Questions