home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeJava and XML, 2nd EditionSearch this book

7.5. Gotcha!

Not to disappoint, I want to warn you of some common JDOM pitfalls. I hope this will save you a little time in your JDOM programming.

7.5.2. Null Return Values

Another interesting facet of JDOM, and one that has raised some controversy, is the return values from methods that retrieve element content. For example, the various getChild( ) methods on the Element class may return a null value. I mentioned this, and demonstrated it, in the PropsToXML example code. The gotcha occurs when instead of checking if an element exists (as was the case in the example code), you assume that an element already exists. This is most common when some other application or component sends you XML, and your code expects it to conform to a certain format (be it a DTD, XML Schema, or simply an agreed-upon standard). For example, take a look at the following code:

Document doc = otherComponent.getDocument( );
String price = doc.getRootElement( ).getChild("item")
                                   .getChild("price")
                                   .getTextTrim( );

The problem in this code is that if there is no item element under the root, or no price element under that, a null value is returned from the getChild( ) method invocations. Suddenly, this innocuous-looking code begins to emit NullPointerExceptions, which are quite painful to track down. You can handle this situation in one of two ways. The first is to check for null values at each step of the way:

Document doc = otherComponent.getDocument( );
Element root = doc.getRootElement( );
Element item = root.getChild("item");
if (item != null) {
    Element price = item.getChild("price");
    if (price != null) {
        String price = price.getTextTrim( );
    } else {
        // Handle exceptional condition
    }
} else {
    // Handle exceptional condition
}

The second option is to wrap the entire code fragment in a try/catch block:

Document doc = otherComponent.getDocument( );
try {
    String price = doc.getRootElement( ).getChild("item")
                                       .getChild("price")
                                       .getTextTrim( );
} catch (NullPointerException e) {
    // Handle exceptional condition
}

While either approach works, I recommend the first; it allows finer-grained error handling, as it is possible to determine exactly which test failed, and therefore exactly what problem occurred. The second code fragment informs you only that somewhere a problem occurred. In any case, careful testing of return values can save you some rather annoying NullPointerExceptions.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.