Error Handling
由于这些属性是当前版本的新增属性,因此建议应用程序catch适合interface的异常,例如,以下示例中的 SAXException。catch应用程序可能会在较早的版本上正常运行,例如,示例代码包含以下方法,该方法检测示例是否与支持新属性的 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 supported
return 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.