Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

DOM Error Handling

Error handling throughout the DOM is handled through a combination of return values and exceptions. All exceptions thrown by DOM methods must be compatible with the DOMException type, which contains a single member named code. The DOM also specifies a list of ExceptionCode values and constant names that must be used by all DOM implementations. The DOM specification outlines which ExceptionCode values can be thrown for a given method and when they should be used. The following Java code fragment illustrates how to catch a DOMException thrown by the createElementNS method of the Document interface:

Document doc = new Document();
try  {
   Element el = doc.createElementNS("urn:foo-bar", "foo");
}
catch(DOMException e) {
   System.out.println(e.code);
}

Certain DOM implementations may automatically map these ExceptionCode values to string descriptions that can be displayed to the user. For example, a given implementation's exception object might allow you to write code that looks like this.

Document doc = new Document();
try  {
   Element el = doc.createElementNS("urn:foo-bar", "foo");
}
catch(DOMException e) {
   System.out.println(e.getDescription());
   e.printStackTrace(System.out);
}

Remember that getDescription and printStackTrace, in this case, are implementation specific and may not be available across different DOM implementations. The only standard member of DOMException is code.

Because certain programming languages and component technologies don't support the standard notion of exceptions (as in Java or C++), the DOM specification leaves the overall exception handling requirements somewhat open. In other words, the specification is flexible in terms of what is required of a conforming DOM implementation. Language bindings that cannot properly deal with exceptions can alternatively use native error reporting mechanisms that map to the ExceptionCode values. DOM implementations may also raise other proprietary exceptions necessary for the implementation's language binding that are not specifically defined in the DOM specification.

  • + Share This
  • 🔖 Save To Your Account