错误处理
原文: https://docs.oracle.com/javase/tutorial/jaxp/properties/error.html
由于属性是当前版本的新属性,因此建议应用程序捕获适合于接口的异常,例如,以下示例中的 SAXException。捕获应用程序可能在旧版本上正常工作,例如,示例代码包含以下方法,该方法检测样例是使用 JDK 版本运行还是支持新属性的 JAXP 实现:
public boolean isNewPropertySupported() {try {SAXParserFactory spf = SAXParserFactory.newInstance();SAXParser parser = spf.newSAXParser();parser.setProperty("http://javax.xml.XMLConstants/property/accessExternalDTD", "file");} catch (ParserConfigurationException ex) {fail(ex.getMessage());} catch (SAXException ex) {String err = ex.getMessage();if (err.indexOf("Property 'http://javax.xml.XMLConstants/property/accessExternalDTD' is not recognized.") > -1){//expected, jaxp 1.5 not supportedreturn false;}}return true;}
如果由于新属性设置的限制而拒绝访问外部资源,则会引发异常,并出现以下格式的错误:
[type of construct]: Failed to read [type of construct] "[name of the external resource]", because "[type of restriction]" access is not allowed due to restriction set by the [property name] property.
例如,如果通过限制 http 协议来拒绝提取外部 DTD,例如: parser.setProperty(“http://javax.xml.XMLConstants/property/accessExternalDTD”,“file”);如果解析器解析包含对“http://java.sun.com/dtd/properties.dtd”的外部引用的 XML 文件,则错误消息如下所示:
External DTD: Failed to read external DTD ''http://java.sun.com/dtd/properties.dtd'', because ''http'' access is not allowed due to restriction set by the accessExternalDTD property.
