Troubleshooting Presentation for IE6/7 | Home | A More Convenient Zend_Registry

Filed under Quick Tips on May 30, 2008 by Joel Potischman

try { go_fish(); } catch(JDOMException){}

In .NET, calling the selectSingleNode() method on XML documents returns a single node if the XPath expression finds a hit, and null if it doesn't.

So imagine my surprise when I found that JDOM in Java throws a JDOMException if no node was found! I think of exceptions as being exceptional events, so the designers of JDOM either disagree, or they think that not finding a node is a truly rare event. I'd argue that JDOM is wrong. Even strongly-typed XML documents can have optional elements, so throwing an exception when you don't find one is a serious escalation on a perfectly foreseeable outcome.

The Go Fish equivalent of selectSingleNode() either gets you the card you asked for, or your opponent squealing "Go Fish!". The JDOM version of Go Fish would instruct your opponent to either return a card or punch you in the face, and would instruct you to defend yourself from being knocked out in case your card wasn't found.

Hence, I wrote the following utility function to return a null result instead of an exception when we don't find our node:

public static Element selectSingleNodeSafe(Object xmlContext, String xPath) {
     try {
          return (Element) XPath.selectSingleNode(xmlContext, xPath);
     } catch (JDOMException e) {
          return null;
     }
}

Post a Comment Digg Del.icio.us

Trackback Pings (TrackBack URL for this entry)

http://www.arc90.com/cgi-bin/mt4/mt-tb.cgi/157.

Comments

Best quick tip ever! I actually laughed out loud. Oh, and I completely agree.

Posted on May 31, 2008 9:50 AM by Doug

Post a Comment:

Troubleshooting Presentation for IE6/7 | Main | A More Convenient Zend_Registry