簡體   English   中英

繼續執行Java代碼以捕獲異常

[英]Continue the java code at catching the exception

我正在編寫一個用於解析XML文件並檢測其UTF-8是否兼容的Java程序。 我已經使該部分正常工作,但是當它捕獲到第一個異常(語法錯誤)時,它將停止執行。 我希望它查找所有錯誤,而不僅僅是第一個。 有什么方法可以記錄錯誤而不是在第一個錯誤上停止它? 這是我的代碼。

 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());
         }
     }

您可以編寫自己的ErrorHandler ,而不將其拋出並將其附加到生成builder (而不是SimpleErrorHandler

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM