[jdom-interest] NoSuch*Exceptions in JDOM

Jools Enticknap jools at jools.org
Fri Jun 16 11:20:20 PDT 2000

On Fri, 16 Jun 2000, bob wrote:

> > if NoSuchElementException is designed, simply to eliminate the need to
> > check for a null, then I would suggest that using a List is just as heavy
> > weight.
> 	It typically for people doing long paths.
> 	elem.getChild("foo").getChild("bar").getChild("baz);

Mmm, OK.

I however __really__ don't like this style.

Given then (albeit abtuse) code like this;

elem.getChild("foo").getChild("bar").getChild("baz").getChild( "bar");

And an exception was thrown due to one of the "bar" elements being
missing, I would not know which getChild() call caused the exception.

But this has been covered before.....

> 	You can wrap that with a single try/catch for the
> 	entire chain.  Otherwise, you have to wrap each
> 	getChild() call with an "if (elem != null)".  Which
> 	turns into a lot of typing.

Or maybe you might do this.

Element target = null;
try {
	target = elem.getChild("foo");
	target = target.getChild("bar");
	target = target.getChild("baz");
catch( NullPointerException npe ) {
	// Print out the exception .....

> 	Also, Exception handling in Java isn't heavy-weight.
> 	It's computationally similar to a normal return, with
> 	an 'isAnException' flag set.  Remember that Java isn't
> 	compiled C++ code.

To a degree, you are correct, however I think that the reference is a
little missplaced :-)

The original comment was based on the thought "I don't want to handle an
exceptional condition at this point as it makes my life hard" and so I
went on to show why in this situation is was a pain to have to place a
call to getChild in a try/catch block.

An in order to achieve this I would have to call
getChildren("foo").size(), which is more expensive than checking a null.

However, I'm still on the fence. Somebody push me :-)


More information about the jdom-interest mailing list