我正在编写一个 java 程序来解析 XML
文件并检测其是否符合 UTF-8
标准。我已经让那部分工作了,但是当它捕获到第一个异常(语法错误)时它停止了执行。我希望它找到所有错误,而不仅仅是第一个错误。有什么办法可以记录错误而不是在第一个错误上停止吗?这是我的代码。
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
)
关于java - 在捕获异常时继续java代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11104129/