错误处理

原文: https://docs.oracle.com/javase/tutorial/jaxp/properties/error.html

由于属性是当前版本的新属性,因此建议应用程序捕获适合于接口的异常,例如,以下示例中的 SAXException。捕获应用程序可能在旧版本上正常工作,例如,示例代码包含以下方法,该方法检测样例是使用 JDK 版本运行还是支持新属性的 JAXP 实现:

  1. public boolean isNewPropertySupported() {
  2. try {
  3. SAXParserFactory spf = SAXParserFactory.newInstance();
  4. SAXParser parser = spf.newSAXParser();
  5. parser.setProperty("http://javax.xml.XMLConstants/property/accessExternalDTD", "file");
  6. } catch (ParserConfigurationException ex) {
  7. fail(ex.getMessage());
  8. } catch (SAXException ex) {
  9. String err = ex.getMessage();
  10. if (err.indexOf("Property 'http://javax.xml.XMLConstants/property/accessExternalDTD' is not recognized.") > -1)
  11. {
  12. //expected, jaxp 1.5 not supported
  13. return false;
  14. }
  15. }
  16. return true;
  17. }

如果由于新属性设置的限制而拒绝访问外部资源,则会引发异常,并出现以下格式的错误:

  1. [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 文件,则错误消息如下所示:

  1. 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.