[jdom-interest] NoSuch*Exceptions in JDOM

Dino Valente dino at 3dstockcharts.com
Thu Jun 15 16:16:13 PDT 2000


At 04:57 PM 6/15/00 -0500, Brett McLaughlin wrote:
>Simon Rade wrote:
> >
> > Hi!
> >
> > Element's methods getAttribute() and getChild() now throws
> > NoSuchElementException and NoSuchAttributeException.
> > Do you think this is better than returning null in such cases?
> > Since it often happens that you don't know whether child or attribute
> > exists and it is very awkward to handle those Exceptions.
>
>Yup. We went over this a bit - you don't want to ever have to really
>check for null in code, it isn't that great of a practice.

I disagree. Doing a try/catch for each optional attribute or element is 
even worse.

>You can
>always do
>
>List children = element.getChildren("elementName");
>
>and check the list's length if you don't want to deal with an Exception.
>
>-Brett

I would suggest creating a utility routine that would deal with this in a 
nicer and more efficient way.

eg:

     /**
     *  Retrieve the child element with name. Return null if it is not found.
     */
     public static Element getChild(Element parent, String name) {
         try {
             return parent.getChild(name);
         } catch (NoSuchElementException e) {
             return null;
         }
     }





More information about the jdom-interest mailing list